Skip to content
thesarfo

Note

Searching

Adding text-based search across multiple fields with SearchFilter.

views 0

Now, what if we want to find products by their title, or something. This is where we use searching. Searching is only used for text-based fields.

First we import the Searchfilter from rest_framework filters. And then we add the Searchfilter to the filter_backends variable. Then we create a variable called search_fields which will contain an array of the fields we want to search by. see below

views.py
from rest_framework.filters import SearchFilter
class ProductViewSet(ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = [DjangoFilterBackend, SearchFilter]
filterset_class = ProductFilter
search_fields = ['title', 'description']