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

相关推荐
iamohenry2 小时前
古早味的心理咨询聊天机器人
python·自然语言处理
Blossom.1185 小时前
移动端部署噩梦终结者:动态稀疏视觉Transformer的量化实战
java·人工智能·python·深度学习·算法·机器学习·transformer
AiXed6 小时前
PC微信协议之AES-192-GCM算法
前端·数据库·python
灵光通码6 小时前
神经网络基本概念
python·神经网络
Petrichor_H_8 小时前
DAY 31 文件的规范拆分和写法
python
咚咚王者9 小时前
人工智能之编程进阶 Python高级:第九章 爬虫类模块
开发语言·python
深蓝海拓9 小时前
使matplot显示支持中文和负号
开发语言·python
AntBlack10 小时前
AI Agent : CrewAI 简单使用 + 尝试一下股票分析
后端·python·ai编程
一眼万里*e10 小时前
搭建本地deepseek大模型
python
1***Q78410 小时前
PyTorch图像分割实战,U-Net模型训练与部署
人工智能·pytorch·python