有没有办法使用 SearchFilter 在 Django-rest-framework 中禁用多重搜索?
默认情况下,如果空格和/或逗号出现在搜索字符串中,django-rf 将应用多重搜索。
xyz.com/?search=x,y
此搜索将返回包含 x 或 y(以逗号分隔)的结果。
我想让它返回的结果包含“x,y”作为字符串的一部分。
最佳答案
很难为此想出一个好的论据和用例,但既然你想实现这样的搜索,你就必须需要它。
我会将现有的 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))
.
这可能会返回您预期的结果
关于python - 在 django rest framework searchfilter 中禁用多重搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54937336/