排序与过滤
查询所有才需要过滤,排序是按照某个规则排序
排序
简单使用
- 导入类
OrderingFilter
- 在视图类重写filter_backends属性,在列表内填入导入的类
- 重写ordering_fields属性,在列表内填入字段
class BookView(ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
filter_backends = [OrderingFilter]
ordering_fields = ['price', 'author','title'] # 可以填很多个
# 按价格正序
http://127.0.0.1:8000/app02/book/?ordering=price
# 按价格倒序
http://127.0.0.1:8000/app02/book/?ordering=-price
过滤
过滤和排序并不冲突,谁先谁后都无所谓
有三种过滤
- drf内置的过滤类
- 第三方的 django-filter
- 自定义的,当业务逻辑比较复杂时可以用
内置的模糊匹配
如下配置,在浏览器输入http://127.0.0.1:8000/app02/normalbook/?search=飘飘
时,会将所有标题和作者名内带飘飘的书筛选出来
class NormalBookView(GenericViewSet, RetrieveModelMixin, ListModelMixin):
serializer_class = BookSerializer
queryset = Book.objects.all()
# 排序 很简单
filter_backends = [SearchFilter]
search_fields = ['title', 'author']
第三方的精准匹配
# 简单使用
1-安装第三方模块
pip install django-filter
2-导入过滤类
from django_filters.rest_framework import DjangoFilterBackend
3-视图类配置
class NormalBookView(GenericViewSet, RetrieveModelMixin, ListModelMixin):
serializer_class = BookSerializer
queryset = Book.objects.all()
filter_backends = [DjangoFilterBackend]
filterset_fields = ['title']
自定义过滤类
# 定义方法
1-定义一个过滤类继承BaseFilterBackend
2-重写filter_queryset,在方法内定义过滤规则
3-返回queryset对象
from rest_framework.filters import BaseFilterBackend
from django.db.models import Q
class CommonFilter(BaseFilterBackend):
# 过滤价格大于xxx,书名带xxx字
def filter_queryset(self, request, queryset, view):
price = request.query_params.get('price', None)
price = int(price)
title = request.query_params.get('title', None)
if price and title:
queryset = queryset.filter(Q(price__gt=price) | Q(title__contains=title))
if price:
queryset = queryset.filter(price__gt=price)
if title:
queryset = queryset.filter(title__contains=title)
# 最后要返回querset对象
return queryset
# 简单使用
# 自定义的过滤器就不需要传入字段了
class NormalBookView(GenericViewSet, RetrieveModelMixin, ListModelMixin):
serializer_class = BookSerializer
queryset = Book.objects.all()
# 排序 很简单
filter_backends = [CommonFilter]
标签:title,price,queryset,filter,过滤,排序,class
From: https://www.cnblogs.com/Hqqqq/p/18149599