Django在fitler过滤不等于的条件

提问

django 在API接口fitler的时候如何过滤 category 不等于6的

解答

为了在AoYuStudentFilter中设置过滤category不等于6的条件,需要使用django_filters库中的exclude方法。不过直接在FilterSet中使用exclude可能不那么直观,因为FilterSet主要设计用来包含符合条件的结果,而不是排除它们。可以通过定义自定义过滤方法来实现这一点。

已经安装了django_filters库并正确配置了Django项目以使用它。

可以通过以下方式在你的FilterSet类中添加一个自定义方法来实现category不等于6的过滤:

python 复制代码
from django_filters import rest_framework as filters
from .models import MyModel

class AoYuStudentFilter(filters.FilterSet):
    # 已有的过滤器...
    
    # 添加一个新的过滤器,用于`category`不等于6
    category_not = filters.NumberFilter(method='filter_category_not')
    
    class Meta:
        model = MyModel
        fields = ['name_student', 'id_student', 'voucher_number', 'from_high_school', 'from_university', 'subjects_before', 'subjects_after', 'from_university_major', 'date_admission_daterangeStart', 'date_admission_daterangeEnd', 'create_datetime_daterangeStart', 'create_datetime_daterangeEnd', 'score_total_min', 'score_total_max', 'category_not']
    
    def filter_category_not(self, queryset, name, value):
        """
        自定义过滤方法,排除category等于指定值的记录
        """
        if value is not None:
            return queryset.exclude(category=value)
        return queryset

在这个例子中,category_not过滤器通过指定method='filter_category_not'来引用一个自定义的过滤方法。这个方法接收queryset、字段名称(name)和过滤值(value),并返回一个排除了特定category值的查询集。

当想要过滤category不等于6的记录时,可以在API请求中添加一个参数category_not=6。这样,filter_category_not方法会被调用,并且queryset会被更新为排除category值为6的记录。

MyModel应替换为实际使用的模型名称,并确保category字段存在于该模型中。此外fields列表中的其它字段名应该根据你的模型实际字段进行相应的调整。

相关推荐
草莓熊Lotso1 天前
Vibe Coding 时代:LangChain 与 LangGraph 全链路解析
linux·运维·服务器·数据库·人工智能·mysql·langchain
zh1570231 天前
JavaScript中WorkerThreads解决服务端计算瓶颈
jvm·数据库·python
代码AI弗森1 天前
一文理清楚“算力申请 / 成本测算 / 并发评估”
java·服务器·数据库
摇滚侠1 天前
expdp 查看帮助
java·数据库·oracle
流年似水~1 天前
MCP协议实战:从零搭建一个让Claude能“看见“数据库的工具服务
数据库·人工智能·程序人生·ai·ai编程
2401_871492851 天前
Vue.js监听器watch利用回调函数处理级联下拉框数据联动
jvm·数据库·python
志栋智能1 天前
超自动化安全:构建智能安全运营的核心引擎
大数据·运维·服务器·数据库·安全·自动化·产品运营
zhoutongsheng1 天前
C#怎么实现Swagger文档 C#如何在ASP.NET Core中集成Swagger自动生成API文档【框架】
jvm·数据库·python
WinterKay1 天前
【开源】我写了一个轻量级本地数据库浏览工具,支持 MySQL/Redis 只读查询
数据库·mysql·开源
zxrhhm1 天前
Oracle 索引完整指南
数据库·oracle