[
课程介绍](_index_)
[
引入DjangoRESTframework](c01-introducetodrf_index)-[Web应用模式](c01-introducetodrf_separatedfrontendandbackend)
[
认识RESTful](c01-introducetodrf_introducetorest)
[
RESTful设计方法](c01-introducetodrf_howtodesignrest)
[
使用Django开发REST接口](c01-introducetodrf_developrestapiwithdjango)
[
明确REST接口开发的核心任务](c01-introducetodrf_coretasktodeveloprestapi)
[
DjangoRESTframework简介](c01-introducetodrf_aboutdrf)
[
DRF工程搭建](c02-drfproject_index)-[环境安装与配置](c02-drfproject_installandconfig)
[
见识DRF的魅力](c02-drfproject_thefirstdrfprogram)
[
Serializer序列化器](c03-serializer_index)-[定义Serializer](c03-serializer_declaring)
[
序列化使用](c03-serializer_serializing)
[
反序列化使用](c03-serializer_deserializing)
[
模型类序列化器ModelSerializer](c03-serializer_modelserializer)
[
视图](c04-view_index)-[Request与Response](c04-view_requestandresponse)
[
视图概览](c04-view_view)
[
视图说明](c04-view_viewintroduction)
[
视图集ViewSet](c04-view_viewset)
[
路由Router](c04-view_routers)
[
其他功能](c05-components_index)-[认证](c05-components_authentication)
[
权限](c05-components_permissions)
[
限流](c05-components_throttling)
[
过滤](c05-components_filtering)
[
排序](c05-components_ordering)
[
分页](c05-components_pagination)
[
版本](c05-components_versioning)
[
异常处理](c05-components_exceptions)
[
自动生成接口文档](c05-components_documents)
[Published with GitBook](https://www.gitbook.com)
课程介绍
分页Pagination
REST framework提供了分页的支持。
我们可以在配置文件中设置全局的分页方式,如:
REST_FRAMEWORK = {'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination','PAGE_SIZE': 100 # 每页数目}
也可通过自定义Pagination类,来为视图添加不同分页行为。在视图中通过pagination_clas属性来指明。
class LargeResultsSetPagination(PageNumberPagination):page_size = 1000page_size_query_param = 'page_size'max_page_size = 10000
class BookDetailView(RetrieveAPIView):queryset = BookInfo.objects.all()serializer_class = BookInfoSerializerpagination_class = LargeResultsSetPagination
注意:如果在视图内关闭分页功能,只需在视图内设置
pagination_class = None
可选分页器
1) PageNumberPagination
前端访问网址形式:
GET http://api.example.org/books/?page=4
可以在子类中定义的属性:
- page_size 每页数目
- page_query_param 前端发送的页数关键字名,默认为”page”
- page_size_query_param 前端发送的每页数目关键字名,默认为None
- max_page_size 前端最多能设置的每页数量 ``` from rest_framework.pagination import PageNumberPagination
class StandardPageNumberPagination(PageNumberPagination): page_size_query_param = ‘page_size’ max_page_size = 10
class BookListView(ListAPIView): queryset = BookInfo.objects.all().order_by(‘id’) serializer_class = BookInfoSerializer pagination_class = StandardPageNumberPagination
127.0.0.1/books/?page=1&page_size=2
2)**LimitOffsetPagination**<br />前端访问网址形式:
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 rest_framework.pagination import LimitOffsetPagination
class BookListView(ListAPIView): queryset = BookInfo.objects.all() serializer_class = BookInfoSerializer pagination_class = LimitOffsetPagination
