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:

class Doctor(models.Model):
    doctor_id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=250)
    institute = models.CharField(max_length=500, blank=True)
    speciality = models.CharField(max_length=500, blank=True)
    address = models.CharField(max_length=250, blank=True)
    country = models.CharField(max_length=50, blank=True)
    latitude = models.FloatField(max_length=50, blank=True, default=0)
    longitude = models.FloatField(max_length=50, blank=True, default=0)
    phone = models.CharField(max_length=250, blank=True)
    degree = models.CharField(max_length=250, blank=True)
    field = models.CharField(max_length=250, blank=True)

    class Meta:
        ordering = ["name"]

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

from rest_framework import generics
from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend
class DoctorAPIView(generics.ListAPIView):
    queryset = Doctor.objects.all()
    serializer_class = DoctorSerializer
    filter_backends = (filters.SearchFilter, DjangoFilterBackend)
    search_fields = ('name', 'speciality', 'institute', 'address')
    filter_fields = ('country',)

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.