Amine Bouhaddi
Amine Bouhaddi

Reputation: 584

Creating a pagination using Django

I'm working on a small project using Django Rest Framework and i'm looking for a way to create pagination using Viewset, i checked the DJR documentation but i couldn't find any answer about doing pagination with Viewsit class,

this is my code :

class ContactView(viewsets.ViewSet):
    
    def list(self, request):
        contactObject = Contact.objects.all()
        contactSerializer = ContactSerializer(contactObject, many=True)
        return Response(contactSerializer.data)

Upvotes: 1

Views: 56

Answers (1)

rahul.m
rahul.m

Reputation: 5854

try this

class ListModelMixin(object):
    """
    List a queryset.
    """
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class ContactView(ListModelMixin, viewsets.GenericViewSet):
    queryset = Contact.objects.all()
    serializer = ContactSerializer

Upvotes: 1

Related Questions