改写 rest_framework 自带的分页器 1.在包目录 utils 下新建 pagination.py 文件,改写分页器:
1 2 3 4 5 6 7 8 from rest_framework.pagination import PageNumberPaginationclass StandarPageNumberPagination (PageNumberPagination ): page_size = 10 max_page_size = 20 page_size_query_param = 'page_size'
2.编辑项目配置文件 dev.py ,在 REST_FREAMWORK = { .. }
列表中添加分页器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ... REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES' : ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication' , 'rest_framework.authentication.SessionAuthentication' , 'rest_framework.authentication.BasicAuthentication' , ), "DEFAULT_PAGINATION_CLASS" :"haoke.utils.pagination.StandarPageNumberPagination" } ...
创建分页视图类、序列化器和路由 创建序列化器 在子应用 goods 目录下新建 serializers.py 文件,内容为:
1 2 3 4 5 6 7 8 9 from rest_framework import serializersfrom .models import SKUclass SKUSerializers (serializers.ModelSerializer): class Meta : model = SKU fields = ('id' , 'name' , 'price' , 'comments' , 'default_image_url' )
创建视图 编辑子应用 goods 目录下的视图文件 views.py,添加如下内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 from django.shortcuts import renderfrom rest_framework.filters import OrderingFilterfrom rest_framework.generics import ListAPIViewfrom .serializers import SKUSerializersclass SKUListView (ListAPIView ): serializer_class = SKUSerializers filter_backends = (OrderingFilter) ordering_fields = ('create_time' , 'price' , 'comments' ) def get_queryset (self ): category_id = self.kwargs['category_id' ] return SKU.objects.filter (category_id=category_id, is_launched=True )
创建路由 在子应用 goods 目录下新建 urls.py 文件,添加:
1 2 3 4 5 6 7 8 from . import viewsfrom django.urls import path, re_pathurlpatterns = [ re_path('^categories/(?P<category_id>\d+)/skus/$' , views.SKUListView.as_view()), ]
总路由注册子路由 编辑项目目录下的 urls.py 文件,在路由列表中添加:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 from django.contrib import adminfrom django.urls import path, includeurlpatterns = [ path('admin/' , admin.site.urls), path('' , include('users.urls' )), path('' , include('verifications.urls' )), path('' , include('areas.urls' )), path('ckeditor/' , include('ckeditor_uploader.urls' )), path('' , include('goods.urls' )), ]