You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除QuerySet中所有指定科目答题数均为null的对象

解决方法

要实现这个过滤需求,核心是构造一个「所有指定科目correct_answers都为null」的条件,然后排除符合该条件的记录。具体可以借助Django的Q对象来动态组合查询条件:

步骤1:导入Q对象

首先确保你已经导入了Django的查询对象:

from django.db.models import Q

步骤2:动态生成组合条件

遍历科目列表,把每个科目对应的{subject}_correct_answers__isnull=True条件用逻辑与(&)组合起来,得到“所有科目都无正确答案”的判断条件:

subjects = ['01', '02']

# 初始化一个空的Q对象
exclude_condition = Q()
for subject in subjects:
    # 逐个添加「该科目correct_answers为null」的条件,用&连接
    exclude_condition &= Q(**{f"{subject}_correct_answers__isnull": True})

步骤3:执行过滤

用QuerySet的exclude方法排除符合上述条件的记录:

new_queryset = q.exclude(exclude_condition)

完整代码示例

from django.db.models import Q

subjects = ['01', '02']
exclude_condition = Q()
for subject in subjects:
    exclude_condition &= Q(**{f"{subject}_correct_answers__isnull": True})

new_queryset = q.exclude(exclude_condition)

补充说明

  • 这里用**把动态生成的字段名转换成Q对象的关键字参数,是Django动态构造查询条件的常用技巧。
  • 如果subjects是空列表,这段代码会排除所有记录(因为空Q对象等价于无条件,exclude无条件会清空QuerySet),如果有需要可以加个判断:
    if subjects:
        # 生成条件并过滤
        exclude_condition = Q()
        for subject in subjects:
            exclude_condition &= Q(**{f"{subject}_correct_answers__isnull": True})
        new_queryset = q.exclude(exclude_condition)
    else:
        # 科目列表为空时,返回原QuerySet
        new_queryset = q
    

内容的提问来源于stack exchange,提问作者mecdeality

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 19:05:31