drf提供的过滤
- 引入
from rest_framework.filters import BaseFilterBackend
- 情景代码(过滤查询)
1 class CourseFilter(BaseFilterBackend): 2 3 def filter_queryset(self,request, queryset, view): 重写filter_queryset 4 extra = {} 5 6 category_id = str(request.query_params.get("category_id")) # query_params 相当于 GET 7 8 if not category_id.isdigit() or category_id == "0": 9 extra = extra 10 else: 11 extra.update({"course_category_id":category_id}) 12 13 return queryset.filter(**extra) # 必须返回queryset
- 挂载
1 class CourseView(ModelViewSet): 2 3 filter_backends = [CourseFilter,]
搜索
- 引入
from rest_framework.filters import SearchFilter
- 挂载
filter_backends=(SearchFilter,)
- 直接指定查询字段
search_fields = ('name',)
排序
- 与搜索相似
from rest_framework.filters import OrderingFilter filter_backends = (OrderingFilter,) ordering_fields = ('name',)