Django REST Framework 学习笔记(十五):分页组件

  • Title(EN): Django REST Framework Learning Notes (15): Pagination
  • Author: dog2

基本信息

  • 源码 rest_framework.pagination
  • 官方文档 API Guide - Pagination
  • 本文demo代码Github

DRF分页类

基础分页类 PageNumberPagination

urls.py

1
2
3
4
5
6
7
from django.urls import path

from . import views

urlpatterns = [
path('cars/', views.CarListAPIView.as_view()), # 基础分页
]

views.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from rest_framework.generics import ListAPIView

from . import models, serializers, paginations

# 基础分页 PageNumberPagination
class CarListAPIView(ListAPIView):
# 如果queryset没有过滤条件,就必须 .all(),不然分页会出问题
queryset = models.Car.objects.all()
serializer_class = serializers.CarModelSerializer

# 分页组件 - 给视图类配置分页类即可 - 分页类需要自定义,继承drf提供的分页类即可
pagination_class = paginations.MyPageNumberPagination

#eg:/cars/ 显示第一页三条
#/cars/?page=2&page_size=4 每页显示4条,显示第二页的4条

偏移分页类 LimitOffsetPagination

urls.py

1
2
3
4
5
6
7
from django.urls import path

from . import views

urlpatterns = [
path('cars1/', views.CarListAPIView1.as_view()), # 偏移分页
]

views.py

1
2
3
4
5
6
7
8
# 偏移分页 LimitOffsetPagination
class CarListAPIView1(ListAPIView):
# 如果queryset没有过滤条件,就必须 .all(),不然分页会出问题
queryset = models.Car.objects.all()
serializer_class = serializers.CarModelSerializer

# 分页组件 - 给视图类配置分页类即可 - 分页类需要自定义,继承drf提供的分页类即可
pagination_class = paginations.MyLimitOffsetPagination

游标分页类 CursorPagination

urls.py

1
2
3
4
5
6
7
from django.urls import path

from . import views

urlpatterns = [
path('cars2/', views.CarListAPIView2.as_view()), # 游标分页
]

views.py

1
2
3
4
5
6
7
8
# 游标分页 CursorPagination
class CarListAPIView2(ListAPIView):
# 如果queryset没有过滤条件,就必须 .all(),不然分页会出问题
queryset = models.Car.objects.all()
serializer_class = serializers.CarModelSerializer

# 分页组件 - 给视图类配置分页类即可 - 分页类需要自定义,继承drf提供的分页类即可
pagination_class = paginations.MyCursorPagination