1 排序和过滤源码分析
继承了GenericAPIView+ListModelMixin,只要在视图类中配置filter_backends它就能实现过滤和排序
- drf内置的过滤类(SearchFilter),排序类(OrderingFiler)
- django-filter
过滤
内置过滤:特点模糊查找
from rest_framework.filters import SearchFilter
class BookViewSet(ViewSetMixin, ListAPIView):
queryset = models.Book.objects
serializer_class = BookModelSerializer
authentication_classes = [LoginAuth, ]
# throttle_classes = [IPThrottling, ]
filter_backends = [SearchFilter]
search_fields = ['name', 'price', ]
- 第三方过滤:不支持模糊查询,是精准匹配
- 1.安装三方插件
- 2 使用模块 from django_filters.rest_framework import DjangoFilterBackend
-3 在配置文件中配置(settings.py)
INSTALLED_APPS = [
...
'django_filters', # 需要注册应用,
]
- 4 在视图中使用
class BookViewSet(ViewSetMixin, ListAPIView):
queryset = models.Book.objects
serializer_class = BookModelSerializer
authentication_classes = [LoginAuth, ]
filter_backends = [DjangoFilterBackend, ]
filter_fields = ['name', 'price']
自定义:写一个类,继承BaseFilterBackend,重写filter_queryset,返回的qs对象,就是过滤或排序后的
from rest_framework.filters import BaseFilterBackend
from django.db.models import Q
class Myfilter(BaseFilterBackend):
def filter_queryset(