一、分页
当访问的数据量特别大的时候,我们需要对数据进行分页显示,可以通过如下三种方式进行,分别介绍如下:
1、根据页码分页
url代码:
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^pagertest/',views.PagerView.as_view()), ]
视图代码:
from django.shortcuts import render from rest_framework.views import APIView from .models import UserInfo from rest_framework.response import Response from rest_framework import serializers from rest_framework.pagination import PageNumberPagination class MyPagination(PageNumberPagination): page_size = 2 #默认每页显示数据条数 page_query_param = "page" #第几页参数,在url中设置 page_size_query_param = "page_size" #定制每页显示的数据条数的参数,在url中设置 class PagerSerialize(serializers.ModelSerializer): '''数据序列化类''' class Meta: model = UserInfo fields = "__all__" depth = 2 #用于显示关联字段的对应的表的详细内容 class PagerView(APIView): def get(self,request,*args,**kwargs): user_list=UserInfo.objects.all() #根据url参数,获取分页数据 obj=MyPagination() page_user_list=obj.paginate_queryset(user_list,request,self) #数据进行序列化 ser=PagerSerialize(instance=page_user_list,many=True) response=obj.get_paginated_response(ser.data) #返回带上下页连接的数据 return response # return Response(ser.data)