Oskar Oskar - 1 year ago 94
Python Question

Paginating a list returned by a ViewSet in Django Rest Framework

I have created a

class with a overridden
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?

I've the following setup:

'DEFAULT_PAGINATION_CLASS': '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"'
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
since they have a specified queryset, but how do I paginate a list?

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download