I'm using djangorestframework with mysql database. I have a view that returns a list based on a search query param. I'm using rest_frameworks.filters SearchFilter for the search based filtering. Here's my view:
from rest_framework import filters
from rest_framework.generics import ListAPIView
...
class FooListView(ListAPIView):
serializer_class = SymbolSerializer
queryset = Symbol.objects.all()
filter_backends = [filters.SearchFilter]
search_fields = ['field_A', 'field_B', 'field_C']
An example URL to call is:
http://localhost:8000/symbols/symbols/?search=bird
Now everything works fine but I need a feature that filters.SearchFilter doesn't support. I want my search to be ordered by priority of search_fields.
For example here's two records:
foo1 : {"field_A": "any", "field_B": "many", "field_C": "bar", "id": 3}
foo2 : {"field_A": "many", "field_B": "any", "field_C": "bar", "id": 4}
Now when I do a search with search='many' param, I want the view to return me a list which foo2 record is higher that foo1 ( like this [foo2, foo1] ) because I want the search's priority to be field_A score but It just returns me a list that is sorted by id ([foo1, foo2]).
Any help?
I just stumbled into this same exact problem.
My solution was to tweak the searching logic of DRF's
filters.SearchFiltera little bit using inspiration from this response and ended up with the following custom filter class:Use
filter_backends = [PrioritizedSearchFilter]and you're set.