SoFunction
Updated on 2024-11-21

Django Rest framework three kinds of paging explained in detail

preamble

We have tens of millions of pieces of data in our database that need to be displayed, and we can't just read them all out of the database.
Because this puts a huge strain on memory and can easily overflow it, we want to fetch little by little.

Similarly, the same applies to the display, where we are bound to paginate the data.

In this article, we will talk about the three types of paging that DRF provides us with.

global configuration

REST_FRAMEWORK = {
  # Effective for all pagers, but low priority
  'PAGE_SIZE': 5, # 5 data per page
}

We start by preparing the data for testing paging and the serialization class
data sheet

from  import models

class Test():
  """Data table for testing paging"""
  name = (max_length=64)

Generate table records:

# Calling Django environments in Python scripts
import os

if __name__ == '__main__':
  # Execute directly after changing the following '' to the corresponding name of the project to generate the record.
  ('DJANGO_SETTINGS_MODULE', > '')
  import django
  ()
  from  import Test # Import data tables
  [(name="Flowering Bones%s" % str(i)) for i in range(100)]

serialized class (computing)

from rest_framework.serializers import ModelSerializer
from  import Test # Import data tables

class TestSerializer(ModelSerializer):
  """Serialization class for testing paging"""
  class Meta:
    model = Test
    fields = '__all__'

The first PageNumberPagination checks the nth page and displays n pieces of data per page.

Step 1 Pager Configuration File

from rest_framework import pagination

class PageNumberPagination():
  """Look up page n, displaying n data per page."""
  page_size = 10 # Specify how many pieces of data to display per page
  page_size_query_param = 'size' # Parameters for the number of bars per page in the URL parameters
  page_query_param = 'page' # Parameters for page numbers in URLs
  max_page_size = None # Maximum number of data per page

Step 2 View File

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.serializers import ModelSerializer
from  import Test # Import data tables
from blog import pagination # Import the above paging configuration

class Test01View(APIView):
  def get(self, request):
    queryset = ()

    # 1. Instantiate the pager object
    page_obj = ()

    # 2. Use your own configured pager to call the paging method for paging
    page_data = page_obj.paginate_queryset(queryset, request)

    # 3. Serialize our paged data.
    ser_obj = TestSerializer(page_data, many=True)

    # 4. Return data
    # return Response(ser_obj.data)

    # 4. return to previous/next linked page
    return page_obj.get_paginated_response(ser_obj.data)

Step 3 Access testing


As shown above, after specifying page=10&size=5, the corresponding data is returned.
***

Second LimitOffsetPagination At the nth position, look backward n pieces of data

Step 1 Pager Configuration File

from rest_framework import pagination

class LimitOffsetPagination():
  """At the nth position, look up n pieces of data backward."""
  default_limit = 1 # Specify the default number of items to look up
  limit_query_param = 'limit' # Parameters in the URL that specify how many pieces of data to look up
  offset_query_param = 'offset' # Parameters in the URL that specify which data to start looking up from
  max_limit = 999 # Maximum number of data to be displayed

Step 2 View File

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.serializers import ModelSerializer
from  import Test # Import data tables
from  import LimitOffsetPagination # Import the above paging configuration


class Test02View(APIView):
  def get(self, request):
    queryset = ()

    # 1. Instantiate the pager object
    page_obj = LimitOffsetPagination()

    # 2. Use your own configured pager to call the paging method for paging
    page_data = page_obj.paginate_queryset(queryset, request)

    # 3. Serialize our paged data.
    ser_obj = TestSerializer(page_data, many=True)

    # 4. Return data
    # return Response(ser_obj.data)

    # 4. return to previous/next linked page
    return page_obj.get_paginated_response(ser_obj.data)

Step 3 Access testing

***

Third CursorPagination Encrypted Cursor Pagination

Step 1 Pager Configuration File

from rest_framework import pagination

class CursorPagination():
  """Pagination of encrypted cursors"""
  cursor_query_param = 'cursor' # Cursor (this is an encrypted cursor)
  # ordering = '-id' # Fetch data from back to front
  ordering = 'id'
  page_size = 1 # Number of articles per page

Step 2 View File

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.serializers import ModelSerializer
from  import Test # Import data tables
from  import CursorPagination # Import the above paging configuration

class Test03View(APIView):
  def get(self, request):
    queryset = ()

    # 1. Instantiate the pager object
    page_obj = CursorPagination()

    # 2. Use your own configured pager to call the paging method for paging
    page_data = page_obj.paginate_queryset(queryset, request)

    # 3. Serialize our paged data.
    ser_obj = TestSerializer(page_data, many=True)

    # 4. Return data
    # return Response(ser_obj.data)

    # 4. return to previous/next linked page
    return page_obj.get_paginated_response(ser_obj.data)

Okay, open your browser and test it.

Pages with previous/next buttons can also be generated using the DRF view system.

from rest_framework.viewsets import ModelViewSet

class Test04View(ModelViewSet):
  queryset = ()
  serializer_class = TestSerializer
  pagination_class = CursorPagination # Specifying the Paging Configurator

Below:


is ok.

This is the whole content of this article.