分页
models.py
from django.db import models
class Book(models.Model):
name =models.CharField(max_length=32)
price = models.IntegerField()
publish = models.CharField(max_length=64)
views.py
from rest_framework.generics import ListAPIView
from rest_framework.mixins import CreateModelMixin
from app01.models import Book
from .serializer import BookSerializers
from rest_framework.viewsets import ViewSetMixin
from app01.pagination import MyPageNumberPagination
from rest_framework.generics import ListAPIView
from rest_framework.mixins import CreateModelMixin
from app01.models import Book
from .serializer import BookSerializers
from rest_framework.viewsets import ViewSetMixin
from app01.pagination import MyPageNumberPagination,MyLimitOffsetPagination,MyCursorPagination
class BookView(ViewSetMixin,ListAPIView,CreateModelMixin):
pagination_class=MyPageNumberPagination,MyLimitOffsetPagination,MyCursorPagination
queryset = Book.objects.all()
serializer_class = BookSerializers
url.py
from django.contrib import admin
from django.urls import path
from rest_framework.routers import SimpleRouter
from app01 import views
router=SimpleRouter()
router.register('books',views.BookView,'books')
urlpatterns = [
path('admin/', admin.site.urls),
]
urlpatterns += router.urls
serializer.py
from rest_framework import serializers
from app01.models import Book
class BookSerializers(serializers.ModelSerializer):
class Meta:
model = Book
fields = "__all__"
pagination.py
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination,CursorPagination
#最常用的
class MyPageNumberPagination(PageNumberPagination):
page_size = 3 # 每页显示的条数
page_query_param = 'page' # /books/?page=3 查询第几页的参数
page_size_query_param = 'size'# /books/?page=3&size=4 # 查询第三页,每页显示4条
max_page_size = 10 # 限制通过size查询,最大的条数
#从哪条开始
class MyLimitOffsetPagination(LimitOffsetPagination):
default_limit = 2 # 每页显示的条数
limit_query_param = 'limit' # /books/?limit=4 这一页显示4条数据
offset_query_param = 'offset' # /books/?offset=3&limit=4 # 从第3条开始,取4条数据
max_limit = 4 # 限制最多显示多少条
#适用于大数据的
class MyCursorPagination(CursorPagination):
cursor_query_param = 'cursor'
page_size = 2 #每页显示条数
max_page_size = 3 # 排序,必须是表中得字段
排序 ,过滤
from rest_framework.filters import OrderingFilter,SearchFilter
class BookView(ViewSetMixin, ListAPIView, CreateModelMixin):
pagination_class = MyPageNumberPagination # 必须继承GenericAPIView才有这个类属性
queryset = Book.objects.all()
serializer_class = BookSerializer
排序类的配置
filter_backends=[OrderingFilter,]
指定按哪个字段排序
ordering_fields=['id','price']
# 指定过滤类
filter_backends=[SearchFilter,]
# 指定过滤字段
search_fields=['name','publish']