1.使用rest_framework提供的分页功能
#在当前子应用courses下创建一个分页器的文件paginations.py
from rest_framework.pagination import PageNumberPagination
class CourseListPageNumberPagination(PageNumberPagination):
"""课程列表分页器"""
page_query_param = "page"
page_size = 5
max_page_size = 20
page_size_query_param = "size"
2.视图函数中加载声明的分页器
from .models import Course
from .serializers import CourseModelSerializer
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from .paginations import CourseListPageNumberPagination
class CourseListAPIView(ListAPIView):
"""课程列表API接口"""
queryset = Course.objects.filter(is_show=True, is_deleted=False).order_by("orders","-id")
serializer_class = CourseModelSerializer
filter_backends = [DjangoFilterBackend,OrderingFilter]
filter_fields = ('course_category',)
ordering_fields = ['id', 'students', 'price']
# 指定分页器
pagination_class = CourseListPageNumberPagination
##前端进行测试访问http://127.0.0.1:8000/opt/data7/?page=4 意思就是通过url进行传参的
3.测试,通过postman发送请求
urls路由的写法
path("", views.CourseListAPIView.as_view()),
发送的请求格式
#范例
/user/?course_category=1&ordering="-id"
通过url进行传参