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

相关推荐
周杰伦fans10 分钟前
C# 中的**享元工厂**模式
开发语言·数据库·c#
空空kkk24 分钟前
SpringMVC——拦截器
java·数据库·spring·拦截器
J***51681 小时前
MySql中的事务、MySql事务详解、MySql隔离级别
数据库·mysql·adb
星空的资源小屋1 小时前
VNote:程序员必备Markdown笔记神器
javascript·人工智能·笔记·django
SelectDB1 小时前
Apache Doris 中的 Data Trait:性能提速 2 倍的秘密武器
数据库·后端·apache
i***27951 小时前
Spring boot 3.3.1 官方文档 中文
java·数据库·spring boot
TDengine (老段)1 小时前
TDengine 日期函数 DATE 用户手册
大数据·数据库·物联网·时序数据库·iot·tdengine·涛思数据
q***65692 小时前
PostgreSQL 中进行数据导入和导出
大数据·数据库·postgresql
一 乐2 小时前
助农平台|基于SprinBoot+vue的助农服务系统(源码+数据库+文档)
前端·javascript·数据库·vue.js·ecmascript·springboot
NineData2 小时前
保姆级!Oracle→达梦零停机迁移攻略,5 步操作,业务零影响!
数据库·程序员