解释:过滤其实就是应用于ListModelMixin其为所有内容对其进行过滤的,需要专门安装注册,如127.0.0.1:8000/books/?gid=88
,在所有内容里面得到gid为88的内容
安装:pip install django-filter
配置:
INSTALLED_APPS = [
...
'django_filters', # 需要注册应用,
]
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',)
}
# 不写入到setting.py里面,写入到views.py视图里,写法如下
# filter_backends = DjangoFilterBackend
使用:
class TestGenericAPIView(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
filterset_fields = ['id' ,'time', 'foreign_id']
解释:其是使用过滤的方法,其使用rest_framework过滤里面的排序
使用:http://127.0.0.1:8000/tea/?ordering=-id # -号表示逆序,不加符号表示正序
class TestGenericAPIView(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
filter_backends = [OrderingFilter] # 这里不配置,就需要去setting.py里面配置
ordering_fields = ('id', )
基础分页类:
http://127.0.0.1:8000/tea/?page=1&page_size=2# page表示第几页,page_size表示一页显示几个
http://127.0.0.1:8000/tea/?limit=2&offset=2 # limit表示每次查多少,offset表示隔开几个开始查
使用方法:
解释:如果配置全局就无需专门写入局部配置,同理配置局部无需专门写入全局,理由(django在APIView父类里面默认会读取全局配置的,如果局部写相当于覆盖全局配置)
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 100 # 每页数目
}
from rest_framework.pagination import PageNumberPagination
class LargeResultsSetPagination(PageNumberPagination):
page_size = 2
page_size_query_param = 'page_size'
max_page_size = 2
class TestGenericAPIView(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
pagination_class = LargeResultsSetPagination