REST Framework 分页
DRF使用分页器
分页模式
rest framework中提供了三种分页模式:
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination, CursorPagination
这里介绍 PageNumberPagination 的使用
全局配置(不灵活,不推荐使用)
settingt.py
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
自定义分页
在视图中进行局部设置
from rest_framework import generics
from rest_framework.pagination import PageNumberPagination
from .serializers import ArticleSerializer
from .models import Article
class StandardResultsSetPagination(PageNumberPagination):
page_size = 10 # 表示每页的默认显示数量
max_page_size = 50 # max_page_size:表示每页最大显示数量,做限制使用,避免突然大量的查询数据,数据库崩溃
page_size_query_param = 'pagesize' # page_size_query_param:表示url中每页数量参数
page_query_param = 'pagenum' # page_query_param:表示url中的页码参数
class ArticleListView(generics.ListCreateAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
pagination_class = StandardResultsSetPagination # 注意不是列表(只能有一个分页模式)
返回带总数的分页
前面实现了基础的分页功能,但是只返回了数据,并没有返回总条数及上一页、下一页的URL,这里我们就实现一下带总数的分页
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from collections import OrderedDict, namedtuple
class LargeResultsSetPagination(PageNumberPagination):
page_size = 10
max_page_size = 100
page_query_param = 'pagenum'
page_query_description = '当前第几页'
page_size_query_param = 'pagesize'
page_size_query_description = '每页条目数'
def get_paginated_response(self, data):
return Response(OrderedDict([
('total', self.page.paginator.count),
('next', self.get_next_link()),
('previous', self.get_previous_link()),
('data', data)
]))
class UserView(APIView):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk') # 获取单挑数据 id 值
ret = {
"data": {
"users": []
},
"meta": {
"status": 200,
"message": ""
}
}
page = LargeResultsSetPagination()
if not pk:
queryset = User.objects.all()
page_user = page.paginate_queryset(queryset=queryset, request=request, view=self)
ser = UserSerializer(instance=page_user, many=True)
ret["data"]["users"] = ser.data
return page.get_paginated_response(ret)
# return Response(ret) # Response 只接受列表,字典,字符串类型的数据
else:
if User.objects.filter(pk=pk):
obj_dict = User.objects.filter(pk=pk).first()
ser = UserSerializer(instance=obj_dict, many=False)
ret["data"]["users"] = ser.data
else:
ret["meta"]["status"] = 500
ret["meta"]["message"] = "系统报错"
return Response(ret)
响应数据结构为:
Django RESTFRAMEWORK的草看文档
1、https://www.jianshu.com/p/ae36184e9925
2、