【问题标题】:Disable multiple search in django restframework search_filter在 django rest 框架搜索过滤器中禁用多重搜索
【发布时间】:2019-07-23 01:20:21
【问题描述】:

有没有办法在 Django-rest-framework 中使用 SearchFilter 禁用多重搜索?

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

xyz.com/?search=x,y

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

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

【问题讨论】:

标签: python django search django-rest-framework


【解决方案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)).

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

【讨论】:

    猜你喜欢
    • 2017-10-06
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    相关资源
    最近更新 更多