Django REST framework — add Custom Pagination

Jo-Yu Liao
Nov 3 · 3 min read

Django 2.2.6, djangorestframework 3.10.3

https://www.django-rest-framework.org/

Django REST framework is a powerful and flexible toolkit for building Web APIs, and it is easy to add your custom pagination.

Before we start, please make sure you already have a Django REST framework project, if you do not have it, please read the quick start of Django REST framework documentation .

According to the Django REST framework documentation, to create a custom pagination serializer class you should subclass pagination.BasePagination and override the paginate_queryset(self, queryset, request, view=None) and get_paginated_response(self, data) methods:

  • The paginate_queryset method is passed the initial queryset and should return an iterable object that contains only the data in the requested page.
  • The get_paginated_response method is passed the serialized page data and should return a Response instance.

Ok, let’s start to make it!

1. Add pagination.py

Create a file named ‘pagination.py’ in your project:

[project_name]/
├── [project_name]/
│ ├── __init__.py
│ ├── settings.py // set custom pagination globally
│ ├── urls.py
│ ├── wsgi.py
│ └── pagination.py <-- add this
├── manage.py
├── [app_name]/
│ ├── __init__.py
│ ├── views.py // return custom pagination data

Make a class named CustomPagination:

pagination.py

2. Apply your custom pagination to views.py

  1. If you want to use custom pagination globally, add it to settings.py
//settings.pyREST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS':
'<project_name>.pagination.CustomPagination'
}

2. Or, apply to a specific views

from rest_framework.generics import GenericAPIView
from project_name.pagination import CustomPagination
class XXXView(GenericAPIView): queryset = XXX.objects.all()
serializer_class = XXXSerializer
pagination_class = CustomPagination <-- here

3. If you want to get the result of pagination and add it into your payload:

from rest_framework.generics import GenericAPIView
from project_name.pagination import CustomPagination

class XXXView(GenericAPIView):
serializer_class = XXXSerializer
queryset = XXX.objects.all()
pagination_class = CustomPagination
def get(self, request): queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
result = self.get_paginated_response(serializer.data)
data = result.data # pagination data
else:
serializer = self.get_serializer(queryset, many=True)
data = serializer.data
payload = {
'return_code': '0000',
'return_message': 'Success',
'data': data
}
return Response(data)

Then you can request the url of view with page and page_size. Here is the demo response:

Moreover, if you request with invalid page, the Django REST framework can handle it. It can save your times to detect the type of parameters.


Jo-Yu Liao

Written by

Love studying, programming, and traveling. Worked in Beijing for 2 years. Now live in Taipei. github: https://github.com/ZoeLiao

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade