When building APIs, users often expect to search through data just like they would in a web app or database. Django Rest Framework provides a powerful and simple tool for this: the SearchFilter
.
In this article, we’ll cover:
-
What
SearchFilter
is -
How it works
-
Step-by-step implementation
-
A complete code example
-
Tips and best practices
-
Common pitfalls to avoid
What is SearchFilter
?
SearchFilter
is a built-in filter backend in Django Rest Framework that allows you to search across fields using a simple query parameter (?search=...
).
It’s part of DRF’s core and doesn’t require any third-party packages like django-filter
.
⚙️ How Does SearchFilter
Work?
When you define search_fields
in a view or viewset and add SearchFilter
to filter_backends
, DRF will filter the queryset based on the search
query parameter.
Syntax:
GET /api/items/?search=term
It performs case-insensitive containment lookups by default (icontains
in Django ORM).
Step-by-Step: Implementing SearchFilter
Step 1: Import SearchFilter
from rest_framework.filters import SearchFilter
Step 2: Apply SearchFilter
in Your ViewSet
from rest_framework import viewsets
from rest_framework.filters import SearchFilter
from .models import Product
from .serializers import ProductSerializer
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = [SearchFilter]
search_fields = ['name', 'description']
Step 3: Test It
Request:
GET /api/products/?search=laptop
Effect:
Returns products whose name or description contains "laptop" (case-insensitive).
✅ Full Example
models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
serializers.py
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
views.py
from rest_framework import viewsets
from rest_framework.filters import SearchFilter
from .models import Product
from .serializers import ProductSerializer
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = [SearchFilter]
search_fields = ['name', 'description']
urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import ProductViewSet
router = DefaultRouter()
router.register('products', ProductViewSet)
urlpatterns = [
path('api/', include(router.urls)),
]
Advanced Search Field Syntax
You can use prefixes to control the type of lookup:
Prefix | Lookup Used | Example |
---|---|---|
none | icontains |
'title' → title__icontains=value |
= |
iexact |
'=title' → title__iexact=value |
^ |
istartswith |
'^title' → title__istartswith=value |
@ |
Full-text (if supported) | '@body' → full-text search |
Example:
search_fields = ['^name', '=category', 'description']
Tips & Best Practices
Tip | Why It Matters |
---|---|
✅ Index search fields | Improves performance |
✅ Keep search fields concise | Avoid slow queries on large text |
✅ Combine with pagination | Prevents overwhelming the client |
✅ Use multiple fields | Allows users more flexibility |
✅ Add throttling if needed | Prevents abuse on large datasets |
⚠️ Common Pitfalls
Pitfall | Fix |
---|---|
❌ Forgetting to define search_fields |
DRF won't apply filtering |
❌ Using too many or large text fields | May cause performance issues |
❌ Expecting partial matching without proper fields | Use icontains , istartswith , etc. |
❌ Using SearchFilter without filter_backends |
DRF won’t trigger filtering |
Combine with Other Filters
You can use SearchFilter
alongside:
-
DjangoFilterBackend
for exact filtering -
OrderingFilter
for sorting -
Custom filters
filter_backends = [SearchFilter, DjangoFilterBackend, OrderingFilter]
Conclusion
SearchFilter
is a simple yet powerful tool in Django Rest Framework. It adds search capabilities with minimal setup, making your APIs more user-friendly and dynamic.
Whether you're building a product catalog, blog, or searchable directory, SearchFilter
lets you implement keyword search quickly and cleanly.