Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading