Oskar Oskar - 25 days ago 12
Python Question

Paginating a list returned by a ViewSet in Django Rest Framework

I have created a

ViewSet
class with a overridden
list
method like this:

from rest_framework.response import Response
from rest_framework import viewsets

class MyViewSet(views.ViewSet):

def list(self, request):
return Response([
{"id": 1},
{"id": 2},
])


How do I paginate this response?

In
settings.py
I've the following setup:

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'LinkHeaderPagination',
'PAGE_SIZE': 10
}


And
LinkHeaderPagination
is built like this:

from rest_framework import pagination
from rest_framework.response import Response

class LinkHeaderPagination(pagination.PageNumberPagination):
page_size_query_param = 'page_size'

def get_paginated_response(self, data):
next_url = self.get_next_link()
previous_url = self.get_previous_link()

if next_url is not None and previous_url is not None:
link = '<{next_url}>; rel="next", <{previous_url}>; rel="prev"'
elif next_url is not None:
link = '<{next_url}>; rel="next"'
elif previous_url is not None:
link = '<{previous_url}>; rel="prev"'
else:
link = ''

link = link.format(next_url=next_url, previous_url=previous_url)
headers = {'Link': link, 'Count': self.page.paginator.count} if link else {}

return Response(data, headers=headers)


This works great with
ModelViewSets
since they have a specified queryset, but how do I paginate a list?

Answer

You just need to call get_paginated_reponse method on paginator instead of returning Response. If this is a single viewset only

class MyViewSet(views.ViewSet):
    def list(self, request):
        data = [
            {"id": 1},
            {"id": 2},
        ]
        paginator = LinkHeaderPagination()
        page = paginator.paginate_queryset(data, request)
        if page is not None:
            return paginator.get_paginated_response(page)

        return Response(data)
Comments