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

相关推荐
胖达不服输1 小时前
「日拱一码」020 机器学习——数据处理
人工智能·python·机器学习·数据处理
吴佳浩1 小时前
Python入门指南-番外-LLM-Fingerprint(大语言模型指纹):从技术视角看AI开源生态的边界与挑战
python·llm·mcp
吴佳浩2 小时前
Python入门指南-AI模型相似性检测方法:技术原理与实现
人工智能·python·llm
叶 落2 小时前
计算阶梯电费
python·python 基础·python 入门
Python大数据分析@2 小时前
Origin、MATLAB、Python 用于科研作图,哪个最好?
开发语言·python·matlab
编程零零七3 小时前
Python巩固训练——第一天练习题
开发语言·python·python基础·python学习·python练习题
Zonda要好好学习3 小时前
Python入门Day4
java·网络·python
小龙在山东4 小时前
Python 包管理工具 uv
windows·python·uv
weixin_307779134 小时前
批量OCR的GitHub项目
python·github·ocr
孤狼warrior5 小时前
灰色预测模型
人工智能·python·算法·数学建模