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列表中的其它字段名应该根据你的模型实际字段进行相应的调整。

相关推荐
NineData10 小时前
NineData智能数据管理平台新功能发布|2026年1-2月
数据库·sql·数据分析
IvorySQL10 小时前
双星闪耀温哥华:IvorySQL 社区两项议题入选 PGConf.dev 2026
数据库·postgresql·开源
ma_king13 小时前
入门 java 和 数据库
java·数据库·后端
程序设计实验室16 小时前
当人人都能用 AI 写代码时,我为什么选择重回 Django?
django·djangostarter
jiayou6417 小时前
KingbaseES 实战:审计追踪配置与运维实践
数据库
NineData1 天前
NineData 迁移评估功能正式上线
数据库·dba
NineData1 天前
数据库迁移总踩坑?用 NineData 迁移评估,提前识别所有兼容性风险
数据库·程序员·云计算
赵渝强老师1 天前
【赵渝强老师】PostgreSQL中表的碎片
数据库·postgresql
全栈老石2 天前
拆解低代码引擎核心:元数据驱动的"万能表"架构
数据库·低代码
倔强的石头_2 天前
kingbase备份与恢复实战(二)—— sys_dump库级逻辑备份与恢复(Windows详细步骤)
数据库