Python test development django-rest-framework-87. Pagination query offset pagination (LimitOffsetPagination) and cursor pagination (CursorPagination)…

Foreword

The django-rest-framework paginator provides 3 paging methods. The previous article introduced simple paging (PageNumberPagination).
This article continues to introduce the other two paging offset paging (LimitOffsetPagination) and cursor paging (CursorPagination)

Offset Pagination (LimitOffsetPagination)

LimitOffsetPagination is offset paging. When querying, the url address carries two parameters, limit and offset, in the following format

http://localhost:8000/api/v1/goods?limit=100 & offset=10

You can rewrite the LimitOffsetPagination class to define some parameter configurations of the query

  • default_limit = api_settings.PAGE_SIZE #Default number of items
  • limit_query_param = ‘limit’ # When querying, query parameters and specify the number of queries
  • offset_query_param = ‘offset’ # When querying, what is the specified starting position?
  • max_limit = None # When querying, the maximum number of items returned

First import LimitOffsetPagination

# Paginator -- Offset paging
from rest_framework.pagination import LimitOffsetPagination

class MyLimitOffsetPagination(LimitOffsetPagination):
    default_limit = 5 # Set the number displayed on each page to 5, then the query results will return 5 items by default
    limit_query_param = 'limit' # Use limit_query_param first to set the number of displayed items
    offset_query_param = 'offset' # Offset number, when querying, what is the specified starting position?
    max_limit = 20 # When querying, how many items can be returned at most

APIView uses paging query

When writing a query view, serialize it first and then define the pager. When querying, you can bring the parameters /api/v1/goods?limit=100 & amp;offset=10

from rest_framework import serializers
from .models import Goods
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated, AllowAny
# Author-Shanghai Youyou QQ communication group: 717225969
# blog address https://www.cnblogs.com/yoyoketang/


# Serialize Goods model
class GoodsAPISerializer(serializers.ModelSerializer):

    class Meta:
        model = Goods
        fields = '__all__' # Return all fields

#Paginator -- Offset paging
class MyLimitOffsetPagination(LimitOffsetPagination):
    default_limit = 5 # Set the number displayed on each page to 5, then the query results will return 5 items by default
    limit_query_param = 'limit' # Use limit_query_param first to set the number of displayed items
    offset_query_param = 'offset' # Offset number, when querying, what is the specified starting position?
    max_limit = 20 # When querying, the maximum number of items returned



# Query view
class GoodsAPISView(APIView):
    permission_classes = (AllowAny,) # AllowAny allows all users


    def get(self, request, *args, **kwargs):
        '''Return all'''
        page = MyLimitOffsetPagination()
        goods = Goods.objects.all() # Query all
        ret = page.paginate_queryset(goods, request)
        serializer = GoodsAPISerializer2(ret, many=True)
  
        return Response({
            "code": 0,
            "msg": "success!",
            "data": serializer.data
        })

If we visit http://localhost:8000/api/v1/goods?offset=10 & amp;limit=3, then we will fetch 3 pieces of data from the 10th piece of data in the query results.

{
"code": 0,
"msg": "success!",
"data": [{
"id": 109,
"create_time": "2021-01-17 10:14:41",
"update_time": "2021-01-17 10:14:41",
"goodsname": "Getting started with pytest",
"goodscode": "sp_100010",
"merchantid": "10001",
"merchantname": "Youyou Academy",
"goodsprice": 68.8,
"stock": 10000,
"goodsgroupid": 0,
"goodsstatus": 1
}, {
"id": 110,
"create_time": "2021-01-17 10:15:44",
"update_time": "2021-01-17 10:15:44",
"goodsname": "Getting started with pytest",
"goodscode": "sp_100011",
"merchantid": "10001",
"merchantname": "Youyou Academy",
"goodsprice": 68.8,
"stock": 10000,
"goodsgroupid": 0,
"goodsstatus": 1
}, {
"id": 111,
"create_time": "2021-01-17 10:24:13",
"update_time": "2021-01-17 10:24:13",
"goodsname": "Getting started with pytest",
"goodscode": "sp_100012",
"merchantid": "10001",
"merchantname": "Youyou Academy",
"goodsprice": 68.8,
"stock": 10000,
"goodsgroupid": 0,
"goodsstatus": 1
}]
}

Encrypted Cursor Pagination (CursorPagination)

Cursor Pagination is characterized by fast speed, but it cannot specify specific queries.

Define some parameter configurations of the CursorPagination query

  • cursor_query_param = ‘cursor’ # When querying, the specified query method, the default is ‘cursor’
  • page_size = 3 #Number of items displayed on each page
  • page_size_query_param = ‘size’ #Set size query parameters, default None
  • max_page_size = 20 # Maximum number of items displayed
  • ordering = ‘pk’ #Default sorting rule: sort by pk from small to large, -pk means sort from large to small

First import CursorPagination

# Paginator -- Encrypted cursor paging
from rest_framework.pagination import CursorPagination


class MyCursorPagination(CursorPagination):
    page_size = 5 #Default number of items per page
    page_size_query_param = 'size' # Query parameter size
    max_page_size = 20 # Maximum number of items per page
    ordering = 'pk' #Default sorting rule: sort by pk from small to large, -pk means sort from large to small

APIView uses encrypted cursor for paging

You can only query from the first page. When querying, the cursor value of the next page is returned in the result: cursor=encrypted string

from rest_framework import serializers
from .models import Goods
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated, AllowAny
# Author-Shanghai Youyou QQ communication group: 717225969
# blog address https://www.cnblogs.com/yoyoketang/


# Serialize Goods model
class GoodsAPISerializer(serializers.ModelSerializer):

    class Meta:
        model = Goods
        fields = '__all__' # Return all fields

# Paginator -- encrypted cursor paging
class MyCursorPagination(CursorPagination):
    page_size = 5 #Default number of items per page
    page_size_query_param = 'size' # Query parameter size
    max_page_size = 20 # Maximum number of items per page
    ordering = 'pk' #Default sorting rule: sort by pk from small to large, -pk means sort from large to small



# Query view
class GoodsAPISView(APIView):
    permission_classes = (AllowAny,) # AllowAny allows all users


    def get(self, request, *args, **kwargs):
        '''Return all'''
        page = MyCursorPagination()
        goods = Goods.objects.all() # Query all
        ret = page.paginate_queryset(goods, request)
        serializer = GoodsAPISerializer2(ret, many=True)
  
        return Response({
            "code": 0,
            "msg": "success!",
            "next": page.get_next_link(),
            "data": serializer.data
        })
)

When querying, first visit the homepage http://localhost:8000/api/v1/goods?size=3

{
"code": 0,
"msg": "success!",
"next": "http://localhost:8000/api/v1/goods?cursor=cD0xNA== & amp;size=3",
"data": [{
"id": 1,
"create_time": "2021-01-17 15:14:25",
"update_time": "2021-01-19 15:55:17",
"goodsname": ""Selenium Beginner to Master"--Modify the course name",
"goodscode": "sp_100049",
"merchantid": "10001",
"merchantname": "Youyou Academy",
"goodsprice": 49.0,
"stock": -444,
"goodsgroupid": 0,
"goodsstatus": 1
}, {
"id": 13,
"create_time": "2021-01-16 20:12:36",
"update_time": "2021-01-17 09:41:05",
"goodsname": ""Selenium Beginner to Master"",
"goodscode": "sp_100008",
"merchantid": "10001",
"merchantname": "Youyou Academy",
"goodsprice": 49.9,
"stock": 100,
"goodsgroupid": 0,
"goodsstatus": 1
}, {
"id": 14,
"create_time": "2021-01-16 20:12:42",
"update_time": "2021-01-17 09:41:05",
"goodsname": ""Selenium Beginner to Master"",
"goodscode": "sp_100009",
"merchantid": "10001",
"merchantname": "Youyou Academy",
"goodsprice": 49.9,
"stock": 100,
"goodsgroupid": 0,
"goodsstatus": 1
}]
}

The cursor value of the next page (encrypted string, automatically generated) is automatically generated from the returned result, so you can access the next page of data based on next.

http://localhost:8000/api/v1/goods?cursor=cD0xNA== & amp;size=3

The advantage of encrypted cursor paging is high security. You must get the cursor=encrypted string each time to access the data on the next page.