Commit b42b2abc authored by Hamza Dely's avatar Hamza Dely
Browse files

[note_kfet/filters] Simplification du NoteSearchFilter

parent aed0dc81
......@@ -12,7 +12,7 @@ from django.db.models.constants import LOOKUP_SEP
from rest_framework import filters
from rest_framework.compat import distinct
from note_kfet.utils import escape_regex
from note_kfet.utils import escape_regex, to_bool
class NoteSearchFilter(filters.SearchFilter):
......@@ -20,45 +20,13 @@ class NoteSearchFilter(filters.SearchFilter):
une recherche brute ou une recherche par expression régulière
en commençant à chercher au début d'un mot
def get_regex_mode(self, request):
return strtobool(request.query_params.get('regex', 'false'))
def construct_search(self, field_name):
return LOOKUP_SEP.join([field_name, 'iregex'])
def filter_queryset(self, request, queryset, view):
search_fields = getattr(view, 'search_fields', None)
use_regex_mode = self.get_regex_mode(request)
search_terms = self.get_search_terms(request)
if not search_fields or not search_terms:
return queryset
search_terms = [
def get_search_terms(self, request):
use_regex_mode = to_bool(request.query_params.get('regex', 'false'))
return [
"^%s" % (
search_term if use_regex_mode else escape_regex(search_term)
) for search_term in search_terms
) for search_term in super().get_search_terms(request)
orm_lookups = [
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
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment