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

相关推荐
dust_and_stars几秒前
为什么ubuntu24 snap install code-server 不需要--classic?
网络·数据库
BomanGe24 分钟前
NSK W1406FA系列长行程高速精密丝杠技术指南
运维·服务器·数据库·经验分享·规格说明书
之歆9 分钟前
MongoDB 深度解析:从原理到实践的完整指南
数据库·mongodb
一 乐10 分钟前
幼儿园管理系统|基于springboot + vue幼儿园管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·幼儿园管理系统
tiancaijiben11 分钟前
阿里云日志服务SLS全流程对接与深度使用指南
网络·数据库
云计算磊哥@14 分钟前
运维开发宝典028-MySQL04数据库热备
数据库·adb·运维开发
五阿哥永琪27 分钟前
正则表达式
数据库·mysql·正则表达式
LaughingZhu35 分钟前
Product Hunt 每日热榜 | 2026-06-13
数据库·mysql
c2385642 分钟前
GDB 进程概念详解(下篇)—— 多进程与进阶调试能力
linux·服务器·数据库
tiancaijiben1 小时前
阿里云云备份(Cloud Backup)全量对接与使用指南
数据库·oracle