Home > Back-end >  Filtering and searching with Django Rest Framework
Filtering and searching with Django Rest Framework

Time:08-10

I'm doing my first DRF project and wondered if it's possible to use the DjangoFilterBackend for filtering specific fields and use a search Filter at the same time. So a request would look something like:

http://localhost:8000/api/v1/test/?search=test&id=27&author=2672

Is it possible to do this with DjangoFilterBackend or would I have to write my own filter logic?

If you need more information on the project itself or my code just let me know :)

CodePudding user response:

Yes, it's possible.

Example:

from rest_framework import filters
from django_filters.rest_framework import DjangoFilterBackend

class ProductViewset(viewsets.ModelViewSet):       
    queryset = Product.objects.all()
    
    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    filterset_fields = ["is_discontinued",]
    search_fields = ["name", "description",]

in filterset_fields enumerate the fields you want to filter by. And in search_fields by which you want to search.

URL:

https://www.myurl.ltd/api/products?is_discontinued=False&search=laptop

More info: DjangoFilterBackend and SearchFilter

  • Related