在Django Restframework search_filter

时间:2019-03-01 03:01:39

标签: python django search django-rest-framework

是否仍然可以使用SearchFilter在Django-rest-framework中禁用多个搜索?

默认情况下,如果搜索字符串上出现空格和/或逗号,则django-rf将应用多个搜索。

  

xyz.com/?search=x,y

此搜索将返回包含x或y(用逗号分隔)的结果。

我想让它返回的结果包含“ x,y”作为字符串的一部分。

1 个答案:

答案 0 :(得分:1)

很难想到一个很好的论据和用例,但是由于您要实现这种搜索,因此必须使用它。 我将继承现有的SearchFilter并重写filter_queryset方法:

 def filter_queryset(self, request, queryset, view):
    search_fields = getattr(view, 'search_fields', None)
    search_terms = self.get_search_terms(request)

    if not search_fields or not search_terms:
        return queryset

    orm_lookups = [
        self.construct_search(six.text_type(search_field))
        for search_field in search_fields
    ]

    base = queryset
    conditions = []
    for search_term in search_terms:
        queries = [
            models.Q(**{orm_lookup: search_term})
            for orm_lookup in orm_lookups
        ]
        conditions.append(reduce(operator.or_, queries))
    queryset = queryset.filter(reduce(operator.and_, conditions))

    if self.must_call_distinct(queryset, search_fields):
        # Filtering against a many-to-many field requires us to
        # call queryset.distinct() in order to avoid duplicate items
        # in the resulting queryset.
        # We try to avoid this if possible, for performance reasons.
        queryset = distinct(queryset, base)
    return queryset

这是该方法的外观。稍微看一下,就会看到以下内容: conditions.append(reduce(operator.or_, queries))

您可以将其更改为: conditions.append(reduce(operator.and_, queries))

这可能会返回您的预期结果