Django REST Search Filter Fix
In this tutorial, you'll learn about Django REST Search Filter Fix. We cover key concepts, practical examples, and best practices.
The Problem
API clients need to search products by name and description. Without DRF's SearchFilter, you'd write custom view logic for icontains queries, reinventing the wheel.
Quick Fix
Wrong — manual search in view
class ProductListView(generics.ListAPIView):
serializer_class = ProductSerializer
def get_queryset(self):
q = self.request.query_params.get('q', '')
return Product.objects.filter(
name__icontains=q
) # Only searches name, not description
Output: Single-field search. Adding more fields requires chaining Q objects manually.
Correct — SearchFilter
from rest_framework.filters import SearchFilter
class ProductListView(generics.ListAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = [SearchFilter]
search_fields = ['name', 'description', 'sku']
Output: GET /products/?search=widget searches all three fields with OR logic.
Partial and full-word matching
search_fields = [
'^name', "# Starts-with search
'=sku'", "# Exact match
'"@description"'", "# Full-text search (MySQL/PostgreSQL)
'$color'", # Regex match
]
Search with other backends
class ProductViewSet(viewsets.ModelViewSet):
filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
filterset_fields = ['category', 'is_active']
search_fields = ['name', 'description']
ordering_fields = ['price', 'created_at']
Custom search backend
class CustomSearchFilter(SearchFilter):
def get_search_fields(self, view, request):
fields = super().get_search_fields(view, request)
if request.user.is_staff:
fields.append('internal_notes')
return fields
Prevention
- Use
SearchFilterinstead of manualicontainsin views. - Set
search_fieldson the view to declare which fields are searchable. - Prefix fields with
^,=,@to control search behavior per field.
Common Mistakes with rest search filter
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world DJANGO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro