DRF分页组件使用逻辑分析
在查看数据列表的API中,如果 数据量 比较大,肯定不能把所有的数据都展示给用户,而需要通过分页展示。
在drf中为我们提供了一些分页相关类:
BasePagination,基类
PageNumberPagination(BasePagination) 支持 /accounts/?page=4&page_size=100 格式的分页
LimitOffsetPagination(BasePagination) 支持 ?offset=100&limit=10 格式的分页
1 PageNumberPagination
http://api.example.org/accounts/?page=4
http://api.example.org/accounts/?page=4&page_size=100
page
表述第几页,page_size
表示每页展示多少数据
2种使用方法:
-
固定每页几个数据,直接使用
PageNumberPagination
和配置文件固定时分页组件会直接读取配置文件中的默认值,无论URL传递的参数名和值是啥都不会改变分页结果
# settings.py REST_FRAMEWORK = { "PAGE_SIZE": 10 }
from app01 import models from rest_framework.views import APIView from rest_framework.request import Request from rest_framework.response import Response from rest_framework import serializers from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination class UserSerializer(serializers.ModelSerializer): class Meta: model = models.UserInfo fields = "__all__" class UserView(APIView): def get(self, request: Request): queryset = models.UserInfo.objects.all() pagination = PageNumberPagination() queryset = pagination.paginate_queryset(queryset, request, self) ser = UserSerializer(instance=queryset, many=True) return Response({"status": True, "data": ser.data})
-
根据URL路由动态自定义每页展示多少数据,需要用到类的继承
自定义时如果不传参数,依旧会读取默认的配置文件
# views.py from app01 import models from rest_framework.views import APIView from rest_framework.request import Request from rest_framework.response import Response from rest_framework import serializers from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination class UserSerializer(serializers.ModelSerializer): class Meta: model = models.UserInfo fields = "__all__" class MyPageNumber(PageNumberPagination): page_size_query_param = "size" class UserView(APIView): def get(self, request: Request): queryset = models.UserInfo.objects.all() pagination = MyPageNumber() queryset = pagination.paginate_queryset(queryset, request, self) ser = UserSerializer(instance=queryset, many=True) return Response({"status": True, "data": ser.data})
2 LimitOffsetPagination
LimitOffsetPagination
通常被应用在例如滑动翻页技术
http://api.example.org/accounts/?limit=100
http://api.example.org/accounts/?offset=400&limit=100
limit
表示当前页展示多少数据,offset
表示从第几条数据之后开始展示
# views.py
from app01 import models
from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework import serializers
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
fields = "__all__"
class UserView(APIView):
def get(self, request: Request):
queryset = models.UserInfo.objects.all().order_by("id")
pagination = LimitOffsetPagination()
queryset = pagination.paginate_queryset(queryset, request, self)
ser = UserSerializer(instance=queryset, many=True)
return Response({"status": True, "data": ser.data})