DEV Community

VivekAsCoder
VivekAsCoder

Posted on

Simple Filtering in DRF.

Filtering

  • The basic way to filter is by overwriting the get_queryset method of Generic Views. > Note that Viewsets also have the generic view.
  • Take a look at this example:
class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        """
        Request obj.: self.request
        How to get that parameters of get request.        
        1. username = self.kwargs['username']
        2. username = self.request.query_params.get('username', None)
        """
        username = self.request.query_params.get('username', None)
        return Purchase.objects.filter(purchaser__username=username)

Enter fullscreen mode Exit fullscreen mode

Search Filter Class

  • Location: form rest_framework.filters import SearchFilter
from rest_framework import filters

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['username', 'email']
Enter fullscreen mode Exit fullscreen mode
  • When you make queries like: http://example.com/api/users?search=russell
  • Then our view will try to username and email match with russell.
  • If you use ['=username'] then it'll try to match exact result.
  • If you use ['^username'] then it'll try to match the results which starts with the given query.

Top comments (1)

Collapse
 
zeedu_dev profile image
Eduardo Zepeda

I'm glad to read a post about DRF, everything seems to be related to javascript these days.