Full answer
Backends are applied in order to the queryset returned by get_queryset():
python
class StudentList(generics.ListAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer
filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
filterset_fields = ["grade", "class_room"] # ?grade=A
search_fields = ["name", "^roll_no"] # ?search=asha (^ means startswith)
ordering_fields = ["name", "score"] # ?ordering=-score
ordering = ["name"] # defaultdjango_filters.rest_framework.DjangoFilterBackendneeds thedjango-filterpackage and"django_filters"inINSTALLED_APPS. For ranges and lookups, write aFilterSet:score_min = NumberFilter(field_name="score", lookup_expr="gte").SearchFilterbuilds an OR oficontainsacrosssearch_fields; prefixes^(startswith),=(exact),@(full text on PostgreSQL),$(regex). Searching related fields works withclass_room__name.OrderingFilteraccepts onlyordering_fields; leaving it unset allows any serializer field, which can expose columns or cause slow unindexed sorts. Always set it.- Invalid filter values return 400 with an error message (django-filter), so clients get feedback.
Design points:
- Authorisation belongs in
get_queryset()(for exampleStudent.objects.filter(school=request.user.school)); filters then apply on top. Never trust a query parameter to scope data. - Set backends globally with
DEFAULT_FILTER_BACKENDSor per view. - Filters on non-indexed columns and unbounded
icontainson large tables are slow; use database indexes, trigram indexes on PostgreSQL, or a search engine. - Combine with pagination so filtered results are returned in pages.
- Document filters: django-filter integrates with drf-spectacular for OpenAPI.
python
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
ROOT_URLCONF=__name__,
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "rest_framework", "django_filters", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.db import models, connection
from django_filters.rest_framework import DjangoFilterBackend, FilterSet, NumberFilter
from rest_framework import generics, serializers
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.test import APIClient
class Student(models.Model):
name = models.CharField(max_length=40)
grade = models.CharField(max_length=2)
score = models.IntegerField()
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
editor.create_model(Student)
for n, g, s in [("Asha", "A", 91), ("Ravi", "C", 58), ("Kiran", "B", 74), ("Meera", "B", 66)]:
Student.objects.create(name=n, grade=g, score=s)
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ["id", "name", "grade", "score"]
class StudentFilter(FilterSet):
min_score = NumberFilter(field_name="score", lookup_expr="gte")
class Meta:
model = Student
fields = ["grade", "min_score"]
class StudentList(generics.ListAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer
filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
filterset_class = StudentFilter
search_fields = ["name"]
ordering_fields = ["name", "score"]
ordering = ["name"]
from django.urls import path
urlpatterns = [path("students/", StudentList.as_view())]
c = APIClient()
names = lambda r: [row["name"] for row in r.json()]
print(names(c.get("/students/")))
print(names(c.get("/students/", {"grade": "B"})))
print(names(c.get("/students/", {"min_score": 70, "ordering": "-score"})))
print(names(c.get("/students/", {"search": "ra"})))
r = c.get("/students/", {"ordering": "password"}) # not whitelisted: ignored
print(r.status_code, names(r))
r = c.get("/students/", {"min_score": "abc"})
print(r.status_code, r.json())
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Requires `pip install djangorestframework`. Also needs `pip install django-filter`. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3, django-filter 26.2): ['Asha', 'Kiran', 'Meera', 'Ravi'] ['Kiran', 'Meera'] ['Asha', 'Kiran'] ['Kiran', 'Meera', 'Ravi'] 200 ['Asha', 'Kiran', 'Meera', 'Ravi'] 400 {'min_score': ['Enter a number.']}
Key points
- filter_backends compose: DjangoFilterBackend, SearchFilter, OrderingFilter
- Whitelist filterset_fields and ordering_fields
- FilterSet gives ranges and custom lookups
- Scope by user in get_queryset(), not through parameters
- Index filtered and sorted columns
Common mistakes
- Leaving ordering_fields unset and exposing every column for sorting
- Scoping data by a query parameter instead of get_queryset()
- Running icontains searches on huge unindexed columns
- Forgetting to add django_filters to INSTALLED_APPS
Follow-ups
- How do you filter across a relationship or with a date range?
- How would you make search fast on PostgreSQL?
- How do you document filters in OpenAPI?
Tips
- Name the three backends
- Mention whitelisting
- Mention scoping in get_queryset