在使用Django rest_framwork中ApiView实现分页并自定义返回数据
自定义分页格式
from rest_framework.views import Response
from collections import OrderedDict
from rest_framework.pagination import PageNumberPagination
class AdaptPagination(PageNumberPagination):
page_size = 10 # 每页数目
page_query_param = 'page' # 前端发送的页数关键字名,默认为"page"
page_size_query_param = 'limit' # 前端发送的每页数目关键字名,默认为None
# max_page_size = 100 # 前端最多能设置的每页数量
def get_paginated_response(self, data):
return Response(OrderedDict([
('count', data.get('count', self.page.paginator.count)),
('next', self.get_next_link()),
('previous', self.get_previous_link()),
('msg', data.get('msg', 'success')),
('code', data.get('code', 0)),
('data', data.get('data', data))
]))
rest_framwork中ApiView实现分页
from basis.serializers import UserSerializer, CabinetsSerializer
from basis.models import Cabinets
from rest_framework.views import APIView
class CabinetsViewSet(APIView):
def get(self, request):
# 获取所有数据
queryset = Cabinets.objects.filter(cabinet=True)
# return MyResponse(data=serializer.data, code=0, msg='success', count=queryset.count())
# 创建分页对象
p = AdaptPagination()
# 在数据库中获取分页数据
pager_roles = p.paginate_queryset(queryset=queryset, request=request, view=self)
#对分页数据进行序列化
serializer = CabinetsSerializer(instance=pager_roles, many=True)
data = {
'msg': '成功',
'code': 0,
'data': serializer.data
}
return p.get_paginated_response(data)
发表评论
共 0 条评论
暂无评论