Skip to content

feat: add pagination to viewsets #9493

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

feat: add pagination to viewsets #9493

wants to merge 1 commit into from

Conversation

paulov59
Copy link

@paulov59 paulov59 commented Aug 7, 2024

Description

Adding Pagination to Viewsets.

Copy link
Member

@auvipy auvipy left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you please share code example, of what this change is going to let us do?

@paulov59
Copy link
Author

paulov59 commented Aug 8, 2024

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)

@paulov59 paulov59 requested a review from auvipy August 8, 2024 19:20
@tomchristie tomchristie closed this Aug 9, 2024
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.

3 participants