DRF之排序
作者:互联网
步骤
第一步:导入内置排序类
from rest_framework.filters import OrderingFilter
第二步:在视图类中配置(必须继承GenericAPIView)
class BookView(GenericViewSet, ListModelMixin): queryset = Book.objects.all() serializer_class = BookSerizlizer filter_backends = [OrderingFilter] ordering_fields = ['price']
第三步:查询
http://127.0.0.1:8000/books/?ordering=-price # 倒序排 http://127.0.0.1:8000/books/?ordering=-price,-id # 先按价格倒序排,如果价格一样,再按id倒序排
过滤和排序同时使用
过滤和排序可以同时用--->因为他们本质是for循环一个个执行,所有优先使用过滤,再使用排序
from rest_framework.filters import OrderingFilter from rest_framework.filters import SearchFilter class BookView(GenericViewSet, ListModelMixin): queryset = Book.objects.all() serializer_class = BookSerizlizer filter_backends = [SearchFilter,OrderingFilter] ordering_fields = ['price', 'id'] search_fields = ['name', 'author']
标签:倒序,ordering,price,OrderingFilter,排序,class,DRF 来源: https://www.cnblogs.com/zhaoyuanshi/p/16120886.html