django drf 过滤器

排序

代码:

python 复制代码
from rest_framework.generics import ListAPIView
from rest_framework.filters import OrderingFilter

class TestListAPIView(ListAPIView):
  queryset = models.Course.objects.filter(is_delete=False).all()
  serializer_class = serializers.TestModelSerializer

  # 配置过滤器类
  filter_backends = [OrderingFilter,]
  # 参与排序的字段: ordering=-score, id
  ordering_fields = ['id', 'score']

前端请求:

http://127.0.0.1:8000/api/test?ordering=-score,id

群查搜索过滤器

代码:

python 复制代码
from rest_framework.generics import ListAPIView
# SearchFilter搜索过滤器
from rest_framework.filters import SearchFilter

class TestListAPIView(ListAPIView):
   queryset = models.Course.objects.filter(is_delete=False).all()
   serializer_class = serializers.FreeCourseModelSerializer

   # 配置搜索过滤器类
   filter_backends = [SearchFilter]
   # 参与搜索的字段: search = liuliuliu (意思是name、status、create_by字段中带liuliuliu就可以了)
   search_fields = ['name', 'status', 'create_by']

前端请求:

http://127.0.0.1:8000/api/test?search=liuliuliu

自定义过滤器

自定义过滤器代码:

python 复制代码
from rest_framework.filters import BaseFilterBackend

class MyFilter(BaseFilterBackend):
   def filter_queryset(self, request, queryset, view):
       # 例如:获取前端想要的数据条数
       limit = request.query_params.get('limit')
       try:
           return queryset[:int(limit)]
       except:
           return queryset

视图代码:

python 复制代码
from rest_framework.generics import ListAPIView
from rest_framework.filters import OrderingFilter

class TestListAPIView(ListAPIView):
   queryset = models.Course.objects.filter(is_delete=False).all()
   serializer_class = serializers.FreeCourseModelSerializer

   # 配置过滤器类, 自定义过滤器类可与自带的共用
   filter_backends = [OrderingFilter, MyFilter]  # MyFilter为自定义过滤器
   # 参与排序的字段: ordering=-score,id
   ordering_fields = ['id', 'score']

前端请求:

http://127.0.0.1:8000/api/test?limit=5

相关推荐
TF男孩10 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在14 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP17 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户8356290780511 天前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
c8i1 天前
python中类的基本结构、特殊属性于MRO理解
python
liwulin05061 天前
【ESP32-CAM】HELLO WORLD
python
Doris_20231 天前
Python条件判断语句 if、elif 、else
前端·后端·python
Doris_20231 天前
Python 模式匹配match case
前端·后端·python
这里有鱼汤1 天前
Python量化实盘踩坑指南:分钟K线没处理好,小心直接亏钱!
后端·python·程序员
大模型真好玩1 天前
深入浅出LangGraph AI Agent智能体开发教程(五)—LangGraph 数据分析助手智能体项目实战
人工智能·python·mcp