分页Pagination
文档:https://www.django-rest-framework.org/api-guide/pagination/
REST framework
提供了分页的支持。
我们可以在配置文件中设置全局的分页方式,如:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 100 # 每页数目
}
也可通过自定义Pagination类,来为视图添加不同分页行为。在视图中通过pagination_class属性来指明。
class LargeResultsSetPagination(PageNumberPagination):
page_size = 1000
page_size_query_param = 'page_size'
max_page_size = 10000
class BookDetailView(RetrieveAPIView):
queryset = BookInfo.objects.all()
serializer_class = BookInfoSerializer
pagination_class = LargeResultsSetPagination
可选分页器
1)LimitOffsetPagination
前端访问网址形式:
GET http://api.example.org/books/?limit=100&offset=400
可以在子类中定义的属性:
- default_limit 默认限制,默认值与PAGE_SIZE设置一致
- limit_query_param limit参数名,默认’limit’
- offset_query_param offset参数名,默认’offset’
- max_limit 最大limit限制,默认None
from book.models import BookInfo
from book.serializers import BookInfoModelSerializer
from rest_framework.viewsets import ModelViewSet
from rest_framework.pagination import LimitOffsetPagination
class BookModelViewSet(ModelViewSet):
queryset = BookInfo.objects.all()
serializer_class = BookInfoModelSerializer
#分页类
pagination_class = LimitOffsetPagination
# http://127.0.0.1:8000/books/?limit=2&offset=4
2)PageNumberPagination
前端访问网址形式:
GET http://api.example.org/books/?page=4
可以在子类中定义的属性:
- page_size 每页数目
- page_query_param 前端发送的页数关键字名,默认为"page"
- page_size_query_param 前端发送的每页数目关键字名,默认为None
- max_page_size 前端最多能设置的每页数量
from book.models import BookInfo
from book.serializers import BookInfoModelSerializer
from rest_framework.viewsets import ModelViewSet
from rest_framework.pagination import PageNumberPagination
#自定义分页类
class PageNum(PageNumberPagination):
page_size = 2 # 默认每页返回的条数
page_size_query_param = 'pagesize' # url中设置 page_size的键,默认为page_size
max_page_size = 10 # 每页返回的最大条数
class BookModelViewSet(ModelViewSet):
queryset = BookInfo.objects.all()
serializer_class = BookInfoModelSerializer
#使用自定义分页类
pagination_class = PageNum
换另外一种写法
class PageNum(PageNumberPagination):
# 开启分页的开关
page_size = 5
# 设置查询字符串的key 相当于 开关.只有设置了这个值.一页多少条记录才生效
page_size_query_param = 'ps'
# 一页最多多少条记录
max_page_size = 20
class PeopleInfoModelViewSet(ModelViewSet):
# 给视图 单独设置权限
# permission_classes = [AllowAny]
#单独设置分页类
pagination_class = PageNum
# queryset = PeopleInfo.objects.all()
# 或者
def get_queryset(self):
return PeopleInfo.objects.all()
# serializer_class = PeopleInfoModelSerializer
# 或者
def get_serializer_class(self):
return PeopleInfoModelSerializer
#http://127.0.0.1:8000/books/?page=1&pagesize=4
以上就是django DRF 的分页设置,希望对你有所帮助。