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

相关推荐
心情好的小球藻3 分钟前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
都叫我大帅哥4 分钟前
LangChain加载HTML内容全攻略:从入门到精通
python·langchain
惜.己15 分钟前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
都叫我大帅哥2 小时前
Python的Optional:让你的代码优雅处理“空值”危机
python
曾几何时`4 小时前
基于python和neo4j构建知识图谱医药问答系统
python·知识图谱·neo4j
写写闲篇儿6 小时前
Python+MongoDB高效开发组合
linux·python·mongodb
杭州杭州杭州7 小时前
Python笔记
开发语言·笔记·python
路人蛃9 小时前
通过国内扣子(Coze)搭建智能体并接入discord机器人
人工智能·python·ubuntu·ai·aigc·个人开发
qiqiqi(^_×)9 小时前
卡在“pycharm正在创建帮助程序目录”
ide·python·pycharm
Ching·9 小时前
esp32使用ESP-IDF在Linux下的升级步骤,和遇到的坑Traceback (most recent call last):,及解决
linux·python·esp32·esp_idf升级