For any kind of list like doctor list, hospital list, pharmacy list etc. we need to search throughout the list regarding on different parameters. Django Rest Framework(DRF) provides us a great efficient search technique. By using we can easily search throughout list.
Suppose I have a model in Django like this:
We can search or filter list data based on doctor name, institute, speciality, address, country. The problem I have faced that I wanna filter the doctor list based on country but search on doctor name, institute, speciality, address simultaneously. I have found a very good solution that I will share with you.
DjangoFilterBackend class provides us the country based filter while SearchFilter class provides us the name, institute, speciality, address based search. So we have just combined this two. It will be very helpful before start seeing the official documentation on Filtering. I think you read the documentation and understand the DjangoFilterBackend SearchFilter. So now lets start combine this two.
In the view class you declare DjangoFilterBackend SearchFilter in filter_backends. For DjangoFilterBackend you declare country field in filter_fields and for SearchFilter you declare doctor name, institute, speciality, address. Use the following code in your view.py:
This will allow the client to filter the items in the list by making queries such as:
- country is the filter_fields. You can add more fields.
- search parameter are search_fields what you given. You can add more fields.
Some useful link that I have followed:
Note: If you have any query or any upgradation of my writing or any mistakes please comment and suggest me. You are warmly welcomed always.