# 分页器 - 全局
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 2
}
from rest_framework.pagination import PageNumberPagination
class pagination(PageNumberPagination):
max_page_size = 3 # 一页最多显示多少条数据
page_size = 1 # 默认一页显示多少条数据
page_query_param = 'aaa' # 参数,用于指示第几页
page_size_query_param = 'size' # 页码的参数名
# 视图集
class StuView(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StuSerializer
# 分页
pagination_class = pagination
需要安装第三方模块
pip install django-filter
安装后在settings中注册过滤
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp', # 注册子应用
'rest_framework', # 注册框架
'corsheaders', # 跨域
'django_filters' # 注册过滤
]
REST_FRAMEWORK = {
# 全局过滤
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}
# 过滤
from django_filters.rest_framework import DjangoFilterBackend
# 视图集
class StuView(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StuSerializer
# 过滤
# 1. 精准过滤
filter_backends = [DjangoFilterBackend] # 指定过滤工具
filter_fields = ['name', 'province'] # 过滤字段
# 过滤
from django_filters.rest_framework import DjangoFilterBackend
import django_filters
# 自定义过滤器
class MyFilter(django_filters.rest_framework.FilterSet):
min = django_filters.NumberFilter(field_name='score', lookup_expr='gte')
max = django_filters.NumberFilter(field_name='score', lookup_expr='lte')
name = django_filters.CharFilter(field_name='name', lookup_expr='icontains')
class Meta:
model = Student
fields = ['min', 'max', 'name']
# 视图集
class StuView(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StuSerializer
# 模糊过滤
filter_backends = [DjangoFilterBackend]
filterset_class = MyFilter
# rest_framework过滤
from rest_framework.filters import SearchFilter
# 视图集
from rest_framework.viewsets import ModelViewSet
class StuView(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StuSerializer
# rest_framework
filter_backends = [SearchFilter]
# 使用外键字段要加__外键的字段
search_fields = ['name','province__id']