- 1.安装
pip install django-filter
- 2.
settings.py
添加配置(全局配置分页、查询、排序引擎)
INSTALLED_APPS = ['django_filters',]
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',
'rest_framework.filters.OrderingFilter'
),
# 设置分页引擎
'rest_framework.pagination.PageNumberPagination'
# 指定每页返回的条数
'PAGE_SIZE': 5
}
- 3.
urils/pagination.py
重写分页类
from rest_framework.pagination import PageNumberPagination
class MyPageNumberPagination(PageNumberPagination):
# 当前页数的key从page修改为p
page_query_param = 'p'
# 默认每页显示的条数为2
page_size = 2
# 把page_size修改为s
page_size_query_param = 's'
# 分页的最大的page_size,每页不能显示超过100条
max_page_size = 100
- 4.
projects/views.py
from django.http import JsonResponse
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from projects.serializer import ProjectSerializer
from .models import Projects
from utils.pagination import MyPageNumberPagination
class ProjectsList(GenericAPIView):
"""
不带参数的请求
"""
# 指定想要的引擎
filter_backends = [DjangoFilterBackend, OrderingFilter]
# 设置过滤字段 (查询字段)
filterset_fields = ['name']
# 设置排序字段
ordering_fields = ['id', 'create_time']
# 定义分页类
pagination_class = MyPageNumberPagination
# 获取queryset
queryset = Projects.objects.all()
serializer_class = ProjectSerializer
def get(self, request):
"""
获取所有接口信息
:param request:
:return:
"""
# 调用get_queryset方法来获取查询集
query = self.get_queryset()
# 对查询集进行过滤(使用的是上面类属性定义的过滤引擎),并覆盖,获取到的是经过排序后的查询集
qs = self.filter_queryset(query)
# 使用paginate_queryset进行分页,返回的是分页后的查询集(如果没有指定分页引擎,那么返回的是None)
page = self.paginate_queryset(qs)
## 判断是否指定了分页引擎,指定了则返回分页后的数据,否则返回只经过过滤引擎处理后的数据
if page is not None:
serializer_obj = self.get_serializer(instance=page, many=True)
## 返回分页后的数据
return self.get_paginated_response(serializer_obj.data)
# 建议使用get_serializer方法来获取序列化器
serializer_obj = self.get_serializer(instance=qs, many=True)
# 响应返回;如果请求没有指定Accept,那么默认返回json
return Response(serializer_obj.data, status=200)
项目/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
# path('admin/', admin.site.urls),
path('', include('projects.urls')),
path('api/', include('rest_framework.urls'))
]
projects/urls.py
from django.urls import path
from rest_framework.routers import DefaultRouter
from projects import views
urlpatterns = [
path('project/', views.ProjectsList.as_view()),
path('project/<int:pk>/', views.ProjectsDetail.as_view()),
]
router = DefaultRouter()
router.register('project', views.ProjectsViewSet)
urlpatterns += router.urls
- 请求:
http://127.0.0.1:8000/project/?name=项目四&p=1&s=3
(字符串无需引号)
示例 -
如果使用没有定义的查询关键字进行查询,那么返回的结果和不带该查询关键字查询的结果一样。比如:
不带查询关键字查询
-
修改
示例max_page_size = 2
,然后请求http://127.0.0.1:8000/project/?p=1&s=3
,返回的实际结果也是2条数据
-
倒序(排序字段需定义了起作用)
根据id倒序
根据创建时间正序
网友评论