Neil
Neil

Reputation: 7202

Django REST Framework Nested Routers - Pagination not working

I have a simple nested router using drf-nested-routers, similar to the example on the readme page. The list view on the nested route does not paginate at all, ignoring my DEFAULT_PAGINATION_CLASS setting. Is this by design? Do nested routes have to manually implement pagination? If I try to call self.get_paginated_response in my nested viewset's list method, I get this error:

AttributeError at /api/foo/13/bar/
'PageNumberPagination' object has no attribute 'page'

Here's my list method in my nested view:

def list(self, request, workplan_pk=None):
        milestones = self.get_queryset()
        wp = get_object_or_404(Workplan, pk=workplan_pk)
        milestones = milestones.filter(workplan=wp)
        return Response(self.get_serializer_class()(milestones, many=True, context={'request': request}).data)

Upvotes: 0

Views: 1066

Answers (1)

Ivan
Ivan

Reputation: 6013

This has nothing to do with routers. Routing is transparent to views, and the only thing they get is a Request object.

You can override ModelViewSet.get_queryset() like this:

class WorkplanMilestones(ModelViewSet):
    #...
    def get_queryset(self):
        wp = get_object_or_404(Workplan, pk=self.kwargs['workplan_pk'])
        return wp.milestones

I am assuming here that the url parameter is called workplan_pk and milestones is the reverse relationship for the milestone model.

This will return workplan's milestones and the rest (including pagination) is handled by ModelViewSet.

Upvotes: 1

Related Questions