Django REST framework 分页
三种分页:根据页码、根据索引、根据加密
http://www.xx.com/courses/?page=1&size=10 http://www.xx.com/courses/?offset=1&limit=10 http://www.xx.com/courses/?page=sdf651sdf3
# 页码越大查询速度越慢,为什么以及如何解决? 原因:页码越大,数据库需要扫描的行数越多,因为每次都是从0开始扫描。 解决: 1、直接限制显示的页数,比如就显示100页,往后翻都不看了; 2、记录当前页数据ID的最小值和最大值,再次分页时,根据ID现行筛选,速度非常快。 第一种简单粗暴,像百度、搜狗都是这样的;第二种就是使用了加密,即使懂
技术的也不知道?page=sdf651sdf3是第几页,不是你想跳到哪页就哪页的。
# urls.py from django.conf.urls import url from appxx import views urlpatterns = [ url(r"^authors/$", views.AuthorView.as_view()), ]
# serializers.py from appxx import models from rest_framework import serializers class AuthorSerializer(serializers.ModelSerializer): class Meta: model = models.Author fields = "__all__"
# views.py from appxx import models from appxx import serializers from rest_framework.views import APIView from rest_framework import pagination class MyPageNumberPagination(pagination.PageNumberPagination): page_query_param = "page" # URL参数名称 page_size = 2 # 每页显示多少条数据 page_size_query_param = "size" # page=2&size=3 --> 第二页显示4、5、6条的数据 max_page_size = 8 # 每页最多显示多少条数据 class AuthorView(APIView): def get(self, request): authors_list = models.Author.objects.all() my_page = MyPageNumberPagination() authors_page = my_page.paginate_queryset(queryset=authors_list, request=request, view=self) s = serializers.AuthorSerializer(authors_page, many=True) return Response(s.data) # return pnp.get_paginated_response(s.data)