繁体   English   中英

搜索过滤器 django drf

[英]Search filter django drf

我想一次将图像作为多个搜索关键字:

视图.py:

class ImageSearchView(generics.ListAPIView):
      authentication_classes = []
      permission_classes = []
      queryset = Image.objects.all()
      serializer_class = ImageSearchSerializer
      filter_backends = (filters.SearchFilter,)
      search_fields = ['image_keyword']

模型.py:

class Image(models.Model):
      license_type = (
         ('Royalty-Free','Royalty-Free'),
         ('Rights-Managed','Rights-Managed')
       )
      image_number = models.CharField(default=random_image_number,max_length=12,unique=True)
      title = models.CharField(default=random_image_number,max_length = 100)
      image = models.ImageField(upload_to = 'image' , default = 'demo/demo.png')
      thumbnail = models.ImageField(upload_to='thumbs', blank=True, null=True)
      category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE)
      shoot = models.ForeignKey(ImageShoot, on_delete=models.CASCADE, related_name='Image', null=True,blank=True)
      image_keyword = models.TextField(max_length=1000)


      def __str__(self):
         return self.title

网址.py:

    path('image_search/',views.ImageSearchView.as_view(), name = 'image_search'),

当我向邮递员提出请求时:

localhost:8000/api/image_search?search=boxing cricket kohli marykom

如果我把 & 放在它们之间,那么它也不起作用:

在此处输入图片说明 我想获取每个包含关键字的图像,例如任何搜索参数

我建议你在这种情况下使用django-filter ,你可以在这里阅读更多:

https://www.django-rest-framework.org/api-guide/filtering/#djangofilterbackend

https://django-filter.readthedocs.io/en/latest/guide/rest_framework.html

如果你不想安装任何东西-你可以覆盖get_queryset你的方法ListAPIView 您需要获取所需的所有查询参数并返回由它们过滤的查询集。 在这种情况下,您的代码将是这样的:

def get_queryset(self, request, *args, **kwargs):
    queryset = Image.objects.all()
    keywords = self.request.query_params.get('search')
    if keywords:
        queryset = queryset.filter(image_keyword__in=keywords.split(','))
    return queryset

在这种情况下,请确保从ImageSearchView类中删除filter_backendssearch_fieldsqueryset字段

django-rest-framework-filters 包与 DjangoFilterBackend 类一起工作,并允许您轻松地跨关系创建过滤器,或为给定字段创建多个过滤器查找类型。

那里阅读

我认为为您准备的部分文档

title__startswith=Who, title__startswith=What
title__startswith%3DWho, title__startswith%3DWhat
(title__startswith%3DWho) | (title__startswith%3DWhat)
%28title__startswith%253DWho%29%20%7C%20%28title__startswith%253DWhat%29
filters=%28title__startswith%253DWho%29%20%7C%20%28title__startswith%253DWhat%29

您是否尝试过像这样多次指定搜索参数? 在这种情况下,它应该“搜索”查询参数最终应该是一个列表。

localhost:8000/api/image_search?search=&search=boxing&search=cricket&search=kohli&search=marykom

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM