How to pass a URL parameter in get_queryset method in Django REST View?

Advertisements

I am trying to pass an ID to a URL in Django to filter my results. For simplicity, I want to list all Foo that are related to a Bar object. I can filter this since Foo has foreign key relationship with Bar.

urlpatterns = [
    path('bar/<int:bar_pk>/foo/', FooListView.as_view()),
]

In my View, I place the ID as parameter to get_queryset() method. However it is not passed down. Can this method not accept URL parameters?

class FooListView(ListAPIView):
    serializer_class = FooSerializer
    permission_classes = (permissions.IsAuthenticated,)
    pagination_class = StandardResultsSetPagination
        
    def post(self, request, bar_pk):
        pass

    def get_queryset(self, bar_pk):
        bar = Bar.objects.get(pk=bar_pk)

        foos = Foo.objects.filter(
            bar=bar).order_by('-id')
        return foos

I receive this error.

get_queryset() missing 1 required positional argument: 'bar_pk'

How can I pass the URL parameter such that I get a filtered result?

>Solution :

It is in the self.kwargs, so:

class FooListView(ListAPIView):
    serializer_class = FooSerializer
    permission_classes = (permissions.IsAuthenticated,)
    pagination_class = StandardResultsSetPagination
        
    def post(self, request, bar_pk):
        pass

    def get_queryset(self):
        return Foo.objects.filter(bar_id=self.kwargs['bar_pk']).order_by('-id')

Leave a ReplyCancel reply