django DRF 组件 排序Ordering
对于列表数据,REST framework提供了OrderingFilter过滤器来帮助我们快速指明数据按照指定字段进行排序。
在类视图中设置filter_backends,使用rest_framework.filters.OrderingFilter过滤器,REST framework会在请求的查询字符串参数中检查是否包含了ordering参数,如果包含了ordering参数,则按照ordering参数指明的排序字段对数据集进行排序。
前端可以传递的ordering参数的可选字段值需要在ordering_fields中指明。
全局配置,settings.py,代码:
"""drf的配置""" # from rest_framework.permissions import AllowAny, IsAuthenticated, IsAdminUser, IsAuthenticatedOrReadOnly REST_FRAMEWORK = { # 中间代码省略。。。。。 # 中间代码省略。。。。。 # # 查询过滤[全局配置] 'DEFAULT_FILTER_BACKENDS': [ # 'django_filters.rest_framework.DjangoFilterBackend', # 过滤 'rest_framework.filters.OrderingFilter', # 排序 ], }
视图代码:
class OrderAPIView(ListAPIView): queryset = Student.objects.all() serializer_class = StudentModelSerializer # 设置当前列表视图的排序字段 ordering_fields = ['id', 'age'] # http://127.0.0.1:8000/component/order/?ordering=-id # -id 表示针对id字段进行倒序排序 # id 表示针对id字段进行升序排序
urls.py,代码:
from django.urls import path, re_path from . import views urlpatterns = [ path("auth/", views.AuthenticationAPIView.as_view()), path("pess/", views.PermissionAPIView.as_view({"get": "list", "post": "create"})), re_path("^pess/(?P<pk>\d+)/$", views.PermissionAPIView.as_view({"get": "retrieve", "put": "update", "delete": "destroy"})), path("throttle/", views.ThorttlingAPIView.as_view()), path("throttle2/", views.Thorttling2APIView.as_view()), path("list/", views.FilterAPIView.as_view()), path("order/", views.OrderAPIView.as_view()), ]
局部设置,在视图类中使用filter_backends设置当前视图类中使用的排序类,views.py,代码:
from rest_framework.filters import OrderingFilter class OrderAPIView(ListAPIView): queryset = Student.objects.all() serializer_class = StudentModelSerializer # 局部设置当前列表视图的排序类[如果使用局部配置项filter_backends会自动覆盖全局配置的DEFAULT_FILTER_BACKENDS] filter_backends = [OrderingFilter] # 设置当前列表视图的排序字段 ordering_fields = ['id', 'age']
上面提到,因为过滤和排序公用了一个配置项filter_backends,所以如果排序和过滤要一起使用的话则必须整个项目,要么一起全局过滤排序,要么一起局部过滤排序。绝不能出现,一个全局,一个局部的这种情况,局部配置项filter_backends会自动覆盖全局配置的DEFAULT_FILTER_BACKENDS。
from rest_framework.viewsets import ModelViewSet from students.models import Student from students.serializers import StudentModelSerializer # Create your views here. from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import OrderingFilter class StuListAPIView(ListAPIView): queryset = Student.objects.all() serializer_class = StudentModelSerializer # 局部设置过滤器类与排序类 filter_backends = [DjangoFilterBackend, OrderingFilter] # 设置当前列表视图的过滤字段 filterset_fields = ["id", "classmate", "sex"] # 设置当前列表视图的排序字段 ordering_fields = ['id', 'age'] # http://127.0.0.1:8000/component/stu/?ordering=-id&classmate=301
路由,代码:
from django.urls import path, re_path from . import views urlpatterns = [ # 中间代码省略。。。。 # 中间代码省略。。。。 path("stu/", views.StuListAPIView.as_view()), ]
浙公网安备 33010602011771号