[Django]-How can i use limit offset pagination for viewsets

5👍

Use ModelViewSet not ViewSet. Also remove your list function it will automatically send response.

from rest_framework.pagination import LimitOffsetPagination

class CountryViewSet(viewsets.ModelViewSet):
    """
    A simple ViewSet for viewing and editing country.
    """ 
    queryset = Country.objects.all()
    serializer_class = CountrySerializer
    pagination_class = LimitOffsetPagination

The actions provided by the ModelViewSet class are .list(),
.retrieve(), .create(), .update(), .partial_update(), and .destroy().

UPDATE

In your settings.py

REST_FRAMEWORK = {
    'PAGE_SIZE': 10,
    # 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
}

UPDATE 2

Alternatively, you can just use paginate_queryset and get_paginated_response

def list(self,request):
    country_data = Country.objects.all()

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

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

Reference:
marking-extra-actions-for-routing

Leave a comment