rest_framwork中ApiView实现分页

 1 from rest_framework.pagination import PageNumberPagination
 2 from .serializers import BookSerilizer
 3 from .models import BookInfo
 4 from rest_framework.views import APIView
 5 # Create your views here.
 6 class MyPageNumberPagination(PageNumberPagination):
 7     page_size=2  #默认两个
 8     max_page_size = 5  #一页显示最大5个
 9     page_query_param = 'page'  #页码
10 
11 class Pager1View(APIView):
12     def get(self,request):
13         #获取所有数据
14         roles = BookInfo.objects.all()
15         #创建分页对象
16         pg = MyPageNumberPagination()
17         #在数据库中获取分页数据
18         pager_roles = pg.paginate_queryset(queryset=roles, request=request,view=self)
19         #对分页数据进行序列化
20         ser = BookSerilizer(instance=pager_roles, many=True)
21         return pg.get_paginated_response(ser.data)  #返回上一页或者下一页

猜你喜欢

转载自www.cnblogs.com/lvye001/p/9938400.html