15.1分页
15.1.1分页的方式(全局分页和局部分类)
局部分页:
# drf局部框架
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 2
}
# 在渲染子数据
class StudentView(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializers
# 局部分页
pagination_class = PageNumberPagination
使用自定义分页器进行分页
pagination_class = pagination
全局分页:
# drf局部框架
REST_FRAMEWORK = {
# 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
# 'PAGE_SIZE': 2
}
15.2过滤
首先引用:
# 在settings.py文件下实施引用
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp', # 子应用
'rest_framework', # drf框架
'corsheaders', # 配置跨域
'django_filters', # 过滤
]
15.2.1过滤的分类 (精准过滤和全局过滤和自定义过滤)
全局过滤:
# 在settings文件下定义
REST_FRAMEWORK = {
# 过滤全区
# 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}
精准过滤:
class StudentView(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializers
# 精准过滤
# filter_backends = [DjangoFilterBackend]
# filter_fields=['pro_name','province']
自定义过滤:
# 自定义过滤器
# import django_filters
# class MyFilter(django_filters.rest_framework.FilterSet):
# # NumberDilter 对数值进行过滤 field_name 过滤字段 lookup_expr 过滤表达式
# # get 大于等于 let小于等于 icontains 不区分大小写的包含
# min_price=django_filters.NumberFilter(field_name='score',lookup_expr='gte')
# max_price=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_price','max_price','name']
class StudentView(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializers
filter_backends = [DjangoFilterBackend]
filterset_class=MyFilter
指定过滤:
class StudentView2(ListAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializers2
# 1.指定使用的过滤工具
filter_backends = [SearchFilter]
# 2.指定过滤字段
search_fields=['province__id','province__pro_name']