DRF过滤类
目录
- DRF过滤类
- OrderingFilter排序
- SearchFilter过滤
- 第三方过滤`django-filter`
- 自定义过滤类
- 使用
OrderingFilter排序
DRF自带的排序类OrderingFilter
必须是继承 GenericAPIView 的视图类才能调用,继承APIView时不能这么配置
# views.py
from rest_framework.filters import OrderingFilterclass publish(GenericViewSet, ListModelMixin):filter_backends = [OrderingFilter]
此时前端请求也要改变
- 根据id排序:
http://127.0.0.1:8000/publish/?ordering=id
- 根据id倒序排序:
http://127.0.0.1:8000/publish/?ordering=-id
如果重写了list方法则该方法不生效,只有用父类的list才会生效`
res = super().list(request, *args, **kwargs)
SearchFilter过滤
过滤类和排序类不冲突
# views.py
from rest_framework.filters import OrderingFilter, SearchFilter class publish(GenericViewSet, ListModelMixin):queryset = models.Publish.objects.all()serializer_class = PublishSerializerfilter_backends = [OrderingFilter, SearchFilter]search_fields = ['name']
此时前端请求也要改
查找name中带’北’的数据:
http://127.0.0.1:8000/publish/?search=北
也可以多个字段模糊匹配
search_fields=['name','publish']
此时?search='北'
会查找name和publish字段中都包含北
的数据
第三方过滤django-filter
安装第三方模块:
pip3 install django-filter
class BookListView(GenericViewSet, ListModelMixin):# 第三方过滤类filter_backends = [DjangoFilterBackend]filterset_fields = ['price', 'name']http://127.0.0.1:8008/publish/?price=66&name=红
自定义过滤类
from rest_framework.filters import BaseFilterBackendclass CommonFilter(BaseFilterBackend):def filter_queryset(self, request, queryset, view):# 完成过滤,返回 qs对象# http://127.0.0.1:8000/publish/?name=北name = request.query_params.get('name', None)if name:queryset = queryset.filter(name__contains=name)return queryset
使用
# views.py
from app.MyFilter import CommonFilterclass publish(GenericViewSet, ListModelMixin):queryset = models.Publish.objects.all()serializer_class = PublishSerializer# 使用自定义的类filter_backends = [CommonFilter]search_fields = ['name']
前端传入
http://127.0.0.1:8000/publish/?name=北