post-thumb

Pagination In Django Rest Framework

Rest Framework includes support for customable pagination style. This allows you to modify how large result sets are split into individual pages of data.

In DRF basically there are three type of paginaiton class

1.PageNumberPagination

2.LimitOffsetPagination

3.CursorPagination

 

1. PageNumberPagination

 

Pagination Global setting

Pagination style may be set globally using DEFAULT_PAGINATION_CLASS and PAGE_SIZE

# settings.py 
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE':5
}

Pagination Per View

you can set the pagination calss on an individual view by using the pagination_calss attribute.

from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
class EmployeeListAPIView(ListAPIView):
    queryset=Employee.objects.all()
    serializer_class=EmployeeSerializer
    pagination_class=PageNumberPagination

You can write separate  class for the pagiantion and can used as per the requirements like :

from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
class EmployeePagination(PageNumberPagination):
    page_query_param='p'  # overide page
    page_size_query_param='records' #overide page_size
    page_size=1  #number of data you want in  a page
    max_page_size=2  #you cannot get more than max_page_size data in particular page
    last_page_strings='end'
class EmployeeListAPIView(ListAPIView):
    queryset=Employee.objects.all()
    serializer_class=EmployeeSerializer
    pagination_class=EmployeePagination

Clients can make request by url like this

http://127.0.0.1:3000/mylist/?records=1&p=1

Other option also too. You can make the custom pagination class and overide the attribute so that you can send the custom response as well:

# paginations.py
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class CustomPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    max_page_size = 50
    page_query_param = 'page_number'
    last_page_strings='end'
    def get_paginated_response(self, data, message="List API"):
        return Response({
            "message": message,
            "count": self.page.paginator.count,
            "next": self.get_next_link(),
            "previous": self.get_previous_link(),
            "data": data
        })

User can call api using request like:

http://127.0.0.1:3000/mylist/?page_number=1&page_size=3

2. LimitoffsetPagination

 This pagination style mirrors the syntax used when looking up multiple database records.

The client include both a "limit" and 'offset" query parameter. The limit indicates the maximum number of items to return and is equivalent to the page_size in pagenumberpagination style , similary offset indicates the starting position of the query in relation to be complete set of unpaginated items.

class EmployeeListAPIView(ListAPIView):
    queryset=Employee.objects.all()
    serializer_class=EmployeeSerializer
    pagination_class= LimitOffsetPagination

user can hit api using url like:

http://127.0.0.1:3000/mylist/?limit=2&offset=1

you can also make custom class and overide the limitoffset pagination attribute as well.

class EmployeePagination(LimitOffsetPagination):
    default_limit=0
    limit_query_param='l'
    offset_query_param='o'
    max_limit=50
    def get_paginated_response(self, data, message="API LIST"):
        return Response({
            "message": message,
            "next": self.get_next_link(),
            "previous": self.get_previous_link(),
            "data": data
        })

class EmployeeListAPIView(ListAPIView):
    queryset=Employee.objects.all()
    serializer_class=EmployeeSerializer
    pagination_class= EmployeePagination

user can hit url like:

http://127.0.0.1:3000/mylist/?l=1&o=1

3.CursorPagination 

 

CursorPagination is a type of pagination available in Django REST Framework (DRF) that allows you to paginate data using a cursor that points to the next page of results. It is useful for situations where you have a large amount of data that may be sorted in different ways.

With CursorPagination, the client sends a request to the server asking for a specific number of items starting from a certain position. The server responds with the requested items and a new cursor that the client can use to request the next set of items.

The cursor-based pagination presents an opaque "cursor" indicator that the calient may use to page through the result set.

This pagination style only presents forward and reverse control and doesnot allows the client to navigate to arbitrary positions.

Here is an example of how to use CursorPagination in DRF:

from rest_framework.generics import ListAPIView
from rest_framework.pagination import CursorPagination
from rest_framework.response import Response
class CustomPagination(CursorPagination):
    page_size = 2
    ordering = 'created'
    cursor_query_param = 'cursor'
    def get_paginated_response(self, data, message="API LIST"):
        return Response({
            "message": message,
            "next": self.get_next_link(),
            "previous": self.get_previous_link(),
            "data": data
        })

class EmployeeListAPIView(ListAPIView):
    queryset=Employee.objects.all()
    serializer_class=EmployeeSerializer
    pagination_class=CustomPagination

user can hit api like :

http://127.0.0.1:3000/mylist/

http://127.0.0.1:3000/mylist/?cursor=cD0yMDIzLTA0LTI4KzA0JTNBMTclM0EyNy45NjgzODIlMkIwMCUzQTAw