Filtering and Searching

Filtering & Searching in DRF (Django REST Framework)

In APIs, sometimes we don’t want to fetch all data. Instead, we want to filter or search based on a condition like:

  • Show only books by a specific author

  • Show books published on a specific date

  • Search books with keyword “Python” in title

Django REST Framework makes this easy using query parameters, django-filter, and search filters.

1. Install and Setup django-filter

First, install the django-filter package:

pip install django-filter

Then add it to your Django project in settings.py:

INSTALLED_APPS = [

    …

    ‘django_filters’,

]

2. Enable Filtering and Searching in DRF

Inside your settings.py, update the REST_FRAMEWORK section to include:

REST_FRAMEWORK = {

    …

    ‘DEFAULT_FILTER_BACKENDS’: [

        ‘django_filters.rest_framework.DjangoFilterBackend’,  # For filtering

        ‘rest_framework.filters.SearchFilter’,                # For searching

    ],

}

3. Update Your View for Filtering & Searching

Go to your books/views.py and update your view class like this:

from rest_framework import viewsets, filters

from django_filters.rest_framework import DjangoFilterBackend

from .models import Book

from .serializers import BookSerializer

 

class BookViewSet(viewsets.ModelViewSet):

    queryset = Book.objects.all()

    serializer_class = BookSerializer

 

    # Adding filtering and searching

    filter_backends = [DjangoFilterBackend, filters.SearchFilter]

 

    # Filter by these fields using exact match

    filterset_fields = [‘author’, ‘published_date’]

 

    # Search by these fields using partial match

    search_fields = [‘title’, ‘author’]

Code Explanation :

from rest_framework import viewsets, filters

  • This imports viewsets (to create REST API views) and filters (used for search functionality like ?search=).

from django_filters.rest_framework import DjangoFilterBackend

  • This imports the filtering backend from django-filter. It allows us to filter data using URL query parameters like ?author=Shahid.

from .models import Book

  • We import the Book model. This is the database table we’ll be filtering and searching.

from .serializers import BookSerializer

  • The BookSerializer is used to convert Book model data into JSON format for API responses.

     

 The Main View

class BookViewSet(viewsets.ModelViewSet):

  • This creates a view class that handles CRUD operations (Create, Read, Update, Delete) for the Book model.

   queryset = Book.objects.all()

  • This line fetches all books from the database as the default list.

   serializer_class = BookSerializer

  • This tells DRF to use the BookSerializer when sending data in API responses.

Filtering and Searching Logic

   filter_backends = [DjangoFilterBackend, filters.SearchFilter]

  • This enables both filtering and searching.

     

    • DjangoFilterBackend: For exact field filters like ?author=Shahid.

       

    • SearchFilter: For partial search like ?search=python.

   filterset_fields = [‘author’, ‘published_date’]

  • You can filter the book list by exact values of these fields.

     

    • Example: /books/?author=Shahid

       

    • Example: /books/?published_date=2024-01-01

       

   search_fields = [‘title’, ‘author’]

  • You can search the book list by partial match in title or author.

     

Example: /books/?search=python will return any books with “python” in title or author name.

What These Do?

  • filterset_fields: Enables exact-match filtering using query parameters
    ➤ Example: ?author=Shahid

     

  • search_fields: Enables partial/keyword search
    ➤ Example: ?search=python

4. How to Test It?

You can test these filters using your browser or Postman by visiting URLs like:

Filter by Author

http://127.0.0.1:8000/api/books/?author=John

Search by Title or Author

http://127.0.0.1:8000/api/books/?search=python

Exercise :

  • Add filtering for grade, and searching for name in your StudentViewSet.

  • Try URLs like:

    • /students/?grade=12

    • /students/?search=Ali

Course Video in English