PageNumberPagination
- Settings.py文件
REST_FRAMEWORK = {
"PAGE_SIZE":2
}
- views.py
from rest_framework.pagination import PageNumberPagination
from rest_framework import serializers
#### 要在settings配置文件中设置REST_FRAMEWORK = {"PAGE_SIZE":2} 参数来启动分页和设置每页数据数量,默认是不启用分页的。
class PagSerializers(serializers.ModelSerializer):
class Meta:
model = models.Article
fields = '__all__'
class PagArticle(APIView):
""" 方式一:分页仅获取数据
def get(self,request,*args,**kwargs):
queryset = models.Article.objects.all()
page_object = PageNumberPagination()
result = page_object.paginate_queryset(queryset,request,self)
ser = PagSerializers(instance=result,many=True)
return Response(ser.data)
"""
""" 方式二:分页数据+分页信息
def get(self,request,*args,**kwargs):
queryset = models.Article.objects.all()
page_object = PageNumberPagination()
result = page_object.paginate_queryset(queryset,request,self)
ser = PagSerializers(instance=result,many=True)
return page_object.get_paginated_response(ser.data)
"""
""" 结果示例输出
{
"count": 6,
"next": "http://127.0.0.1:8000/page/article/?page=3",
"previous": "http://127.0.0.1:8000/page/article/",
"results": [
{
"id": 6,
"title": "xxx科技有限公司",
"summary": "贼拉厉害",
"content": "光明正大的吃霸王餐",
"status": 1,
"cates": 3,
"tag": [
2
]
}
]
}
"""
### 方式三:自定制
def get(self, request, *args, **kwargs):
queryset = models.Article.objects.all()
page_object = PageNumberPagination()
result = page_object.paginate_queryset(queryset, request, self)
ser = PagSerializers(instance=result, many=True)
return Response({"count": page_object.page.paginator.count, "results": ser.data})
访问URL要求:http://api.example.org/accounts/?page=1
LimitOffsetPagination
Views.py
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination
from rest_framework import serializers
class PagSerializers(serializers.ModelSerializer):
class Meta:
model = models.Article
fields = '__all__'
class PagArticle(APIView):
def get(self,request,*args,**kwargs):
queryset = models.Article.objects.all()
page_object = LimitOffsetPagination()
result = page_object.paginate_queryset(queryset,request,self)
ser = PagSerializers(instance=result,many=True)
return Response(ser.data)
访问URL要求:http://api.example.org/accounts/?offset=400&limit=100