django rest framework search filter all fields

2.5k views Asked by At

I have a base model view set which i can handle order, pagination and search functionalities. When i have proper filter backends, i can set ordering_fields, search_fields but my question is that: like i can set ordering_fields = '__all__' isn't it possible to set search_fields for all?

I've looked for deep inside filtering mechanism and came here:

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

    if not search_fields:
        return queryset

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

    for search_term in self.get_search_terms(request):
        or_queries = [models.Q(**{orm_lookup: search_term})
                      for orm_lookup in orm_lookups]
        queryset = queryset.filter(reduce(operator.or_, or_queries))

    return queryset

drf fails on generate search_fields if it is set search_fields='__all__' Is there any other way to provide search by all functionality?

1

There are 1 answers

0
mariodev On

Not possible and it's not a good idea anyway..

One reason is because there can be different types of searching query (__istartswith, __iexact, etc.), which you can set up for each field name.

You can also have different field types which won't necessary support text-base search.

More important - it will result in much slower queries, while you keep adding new fields into the model. It's always better to be explicit, so you know which fields are actually searched upon.

If your searching feature relies on multiple fields, maybe you should consider haystack or look for any other dedicated searching engine.