rest_framwork中ApiView實現分頁
阿新 • • 發佈:2018-11-10
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) #返回上一頁或者下一頁