[Answered ]-Django ReadOnlyModelViewSet: get_querySet getting filtered by pk

2👍

For returning the collection you should not pass in the /{pk}/ since that will try and get a single object with that id, which you have seen.

The proper URL you should be using to get a list of objects is /api/myendpoint/. You can filter the list of objects by using queryset property or get_queryset function. However, we still need to let django know what field and value to filter by.

That’s where filtering by query parameter comes in. You could also filter in the URL string, but it’s a tad more complicated because you’d need to modify your router URLs.

class MyView(viewsets.ReadOnlyModelViewSet):

    def get_queryset(self):
        queryset = MyObj.objects.all()
        filter_value = self.request.query_params.get('field_name', None)
        if filter_value is not None:
            queryset = queryset.filter(field_name=filter_value)
        return queryset

With this code you can hit /api/myendpoint/?field_name=somevalue and it will return a queryset of MyObj model filtering field_name by somevalue.

Leave a comment