DEV Community

VivekAsCoder
VivekAsCoder

Posted on

3 2

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.

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post →

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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay