Skip to content

Adding pagination to viewsets #9496

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed

Conversation

paulov59
Copy link

At the moment, it is not possible to use response pagination with ViewSets, and it is necessary to inherit GenericAPIView. However, the concept of ViewSets is to create only what is necessary and inheriting another class, receiving other methods that may be unnecessary in this context, just to use an attribute does not match this and it also decreases performance, since some data may be cached.

Example of paginated return of action in the current ViewSet structure:

from rest_framework import viewsets, generics
from rest_framework.decorators import action

class MyViewSet(viewsets.ViewSet, generics.GenericAPIView):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

    @action(detail=False, methods=['get'], pagination_class=MyPaginationClass)
    def list_paginated_objects(self, request, *args, **kwargs):
        my_objects = self.paginate_queryset(self.queryset)

        return self.get_paginated_response(MyModelSerializer(my_objects, many=True).data)

With my suggestion, we can perform pagination in the ViewSet, without the need to inherit other classes and their methods.

Example of paginated return of action in the proposed ViewSet structure:

from rest_framework import viewsets
from rest_framework.decorators import action

class MyViewSet(viewsets.ViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

    @action(detail=False, methods=['get'], pagination_class=MyPaginationClass)
    def list_paginated_objects(self, request, *args, **kwargs):
        my_objects = self.paginate_queryset(self.queryset)

        return self.get_paginated_response(MyModelSerializer(my_objects, many=True).data)

@tomchristie
Copy link
Member

Hi Paul, we're not accepting functionality changes to REST framework at this point in time.

https://github.com/encode/django-rest-framework/blob/master/CONTRIBUTING.md

This section of the docs clarifies the behaviour here...

Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular APIView, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the mixins.ListModelMixin and generics.GenericAPIView classes for an example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants