1.urls.py文件-->路由
from pagenation import views from django.urls import re_path urlpatterns = [ re_path('booklist/', views.BasicEditionView.as_view()) ]
2.views.py文件-->视图
# Third-party Library from rest_framework.views import APIView from rest_framework.pagination import PageNumberPagination # Custom Library from pagenation.models import UserInfo from pagenation.service.pagenations import PagerSerializer class MyPaginator(PageNumberPagination): # 默认每页数据条数 page_size = 2 # 使用page作为key传递页码 page_query_param = "page" # 指定每页显示条数 page_size_query_param = "page_size" class BasicEditionView(APIView): def get(self, request, *args, **kwargs): users = UserInfo.objects.all() page_obj = MyPaginator() page_lst = page_obj.paginate_queryset(users, request, self) serialized = PagerSerializer(instance=page_lst, many=True) """ # 只显示每页数据 return Response(serialized.data) """ # 不单显示每页数据,还显示上一页'previous', 下一页'next', 数据总条数'count' response = page_obj.get_paginated_response(serialized.data) return response
3.pagenations.py文件-->序列化组件
#!/usr/bin/env python # -*- coding:utf-8 -*- # Third-party Library from rest_framework import serializers # Custom Library from pagenation.models import UserInfo class PagerSerializer(serializers.ModelSerializer): class Meta: # 指定model model = UserInfo # 自动生成所有字段 fields = '__all__' # 对于外键字段,可以显示 depth = 2
4.models.py文件-->数据库
from django.db import models # Create your models here. class UserInfo(models.Model): name = models.CharField(max_length=32) age = models.CharField(max_length=32) gender = models.CharField(max_length=32)
5.特殊情况处理,针对继承ModelViewSet的视图列处理方法及url的处理方法如下
url处理办法:
from pagenation import views, views2 from django.urls import re_path urlpatterns = [ re_path('booklist/', views.BasicEditionView.as_view( {'get': 'list'} )), ]
视图处理办法:
#!/usr/bin/env python # -*- coding:utf-8 -*- # Third-party Library from rest_framework.pagination import PageNumberPagination from rest_framework.viewsets import ModelViewSet from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer # Custom Library from pagenation.models import UserInfo from pagenation.service.pagenations import PagerSerializer class MyPaginator(PageNumberPagination): # 默认每页数据条数 page_size = 2 # 使用page作为key传递页码 page_query_param = "page" # 指定每页显示条数 page_size_query_param = "page_size" class BasicEditionView(ModelViewSet): # 分页 pagination_class = MyPaginator # 渲染 renderer_classes = [JSONRenderer, BrowsableAPIRenderer] # queryset数据 queryset = UserInfo.objects.all() # 序列化 serializer_class = PagerSerializer