Django drf 排序
18.1 全局配置
配置排序类
REST_FRAMEWORK = {
......
'DEFAULT_FILTER_BACKENDS': (
'rest_framework.filters.OrderingFilter', # 注意这里不能使用django_filters.rest_framework.OrderingFilter,会报错。
),
}
视图
class ExampleView4(ModelViewSet):
queryset = studentsInfo.objects.all()
serializer_class = studentSerializer
ordering_fields = ["id", "age"]
路由
from . import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register("filter", views.ExampleView4, basename="filter")
urlpatterns = [
] + router.urls
访问效果
GET /opt/filter/?ordering=-id
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"id": 17,
"name": "胡歌",
"sex": "男",
"age": 30,
"classroom": "310",
"info": "帅帅帅"
},
{
"id": 16,
"name": "范玉才",
"sex": "男",
"age": 23,
"classroom": "310",
"info": "要做个猛男,要猛!"
},
{
"id": 15,
"name": "彭于晏",
"sex": "女",
"age": 0,
"classroom": "000",
"info": "要做个猛男,要猛!"
},
{
"id": 12,
"name": "孙明辉",
"sex": "男",
"age": 23,
"classroom": "333",
"info": "这个人很懒,什么都没有留下"
},
{
"id": 5,
"name": "闵麒良",
"sex": "男",
"age": 23,
"classroom": "310",
"info": "河工胡歌"
},
{
"id": 4,
"name": "李四",
"sex": "男",
"age": 24,
"classroom": "308",
"info": "这个人很懒,什么也没有留下"
},
{
"id": 3,
"name": "张三",
"sex": "男",
"age": 25,
"classroom": "307",
"info": "这个人很懒,什么也没有留下"
},
{
"id": 2,
"name": "小红",
"sex": "女",
"age": 18,
"classroom": "301",
"info": "这个人很懒,什么也没有留下"
}
]
18.2 局部配置
视图
from rest_framework.filters import OrderingFilter
class ExampleView4(ModelViewSet):
queryset = studentsInfo.objects.all()
serializer_class = studentSerializer
filter_backends = [OrderingFilter]
ordering_fields = ["id", "age"]
路由
from . import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register("filter", views.ExampleView4, basename="filter")
urlpatterns = [
] + router.urls
访问效果
GET /opt/filter/?ordering=-age
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"id": 17,
"name": "胡歌",
"sex": "男",
"age": 30,
"classroom": "310",
"info": "帅帅帅"
},
{
"id": 3,
"name": "张三",
"sex": "男",
"age": 25,
"classroom": "307",
"info": "这个人很懒,什么也没有留下"
},
{
"id": 4,
"name": "李四",
"sex": "男",
"age": 24,
"classroom": "308",
"info": "这个人很懒,什么也没有留下"
},
{
"id": 5,
"name": "闵麒良",
"sex": "男",
"age": 23,
"classroom": "310",
"info": "河工胡歌"
},
{
"id": 12,
"name": "孙明辉",
"sex": "男",
"age": 23,
"classroom": "333",
"info": "这个人很懒,什么都没有留下"
},
{
"id": 16,
"name": "范玉才",
"sex": "男",
"age": 23,
"classroom": "310",
"info": "要做个猛男,要猛!"
},
{
"id": 2,
"name": "小红",
"sex": "女",
"age": 18,
"classroom": "301",
"info": "这个人很懒,什么也没有留下"
},
{
"id": 15,
"name": "彭于晏",
"sex": "女",
"age": 0,
"classroom": "000",
"info": "要做个猛男,要猛!"
}
]
标签:info,classroom,name,age,sex,Django,排序,id,drf
From: https://www.cnblogs.com/minqiliang/p/16822222.html