Search code examples
python-3.xdjango-rest-frameworkdjango-filter

How to get a request object from inside the generic.ListAPIView class for django-filter?


I have a django-filter query running using djangorestframework. The below view function is used for url. But when I get objects at the starting, I want to filter them not only by the parameters the search query has which are username and userid. But I also want to filter based upon who is logged in, which I can get through request object coming from URL.

The function getUsername() works independently but not with other code.

Hence is there a way to access self request in below code. Any help is greatly appreciated.

class userSearch(generics.ListAPIView):

    def getUsername(self):
        return self.kwargs['username']

    serializer_class = UserSerializer
    queryset = UserProfile.objects.filter(professor=User.objects.get(username=self.getUsername()).id).order_by('username')
    filter_backends = (DjangoFilterBackend,SearchFilter)
    filter_fields = (username,userid,userType)
    search_fields = ('username', 'first_name')

Solution

  • Instead of defining the queryset attribute directly, you can override the get_queryset(self) method:

    class userSearch(generics.ListAPIView):
        serializer_class = UserSerializer
        filter_backends = (DjangoFilterBackend, SearchFilter)
        filter_fields = ('username', 'userid')
        search_fields = ('username', 'first_name')
    
        def get_queryset(self):
            username = self.kwargs['username']
            professor = User.objects.get(username=username)
    
            # Here you can do the following thing:
            current_user = self.request.user
    
            # And use it as you wish in the filtering below:
    
            return UserProfile.objects.filter(professor=professor).order_by('username')