1. DRF 分页器
目录
Django DRF 分页器
1. 环境准备
1.1 编辑models.py
from django.db import models
# Create your models here.
class UserInfo(models.Model):
username = models.CharField(verbose_name="姓名", max_length=32)
age = models.SmallIntegerField(verbose_name="年龄")
1.2 编译初始化脚本,为数据库添加数据
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "drf_day3.settings")
django.setup()
from app01 import models
for i in range(200):
models.UserInfo.objects.create(username=f"test-{i}", age=i)
print("Insert data into DB successfully.")
运行后查看数据库,已经成功插入两百条数据。
2. 使用分页器
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination
from app01 import models
from rest_framework import serializers
# Create your views here.
class UserSerilizer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
fields = ["id", "username", "age"]
class UserPagination(PageNumberPagination):
"""
A simple page number based style that supports page numbers as
query parameters. For example:
http://api.example.org/accounts/?page=4
http://api.example.org/accounts/?page=4&page_size=100
"""
page_size_query_param = "page_size"
max_page_size = 20
class UserView(APIView):
def get(self, request):
queryset = models.UserInfo.objects.all()
pagernator = UserPagination()
queryset = pagernator.paginate_queryset(queryset=queryset, request=request, view=self)
ser = UserSerilizer(instance=queryset, many=True)
return Response({"status": True, "data": ser.data})
class InfoPagination(LimitOffsetPagination):
"""
A limit/offset based style. For example:
http://api.example.org/accounts/?limit=100
http://api.example.org/accounts/?offset=400&limit=100
"""
max_limit = 100
class InfoView(APIView):
def get(self, request):
queryset = models.UserInfo.objects.all()
pagernator = InfoPagination()
queryset = pagernator.paginate_queryset(queryset=queryset, request=request, view=self)
ser = UserSerilizer(instance=queryset, many=True)
return Response({"status": True, "data": ser.data})
3. 源码分析
分页器主要有两个功能, PageNumberPagination, LimitOffsetPagination
3.1 LimitOffsetPagination源码分析
url: http://api.example.org/accounts/?offset=400&limit=100
从第四百个object,拿后面一百个 (400-500)
例如在滑动加载数据中使用