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

Django:筛选记录时保留column_three非空的同组重复条目

解决方案

你可以通过Django的ORM查询实现这个需求,核心逻辑是排除那些存在同column_one+column_two且column_three非空的、自身column_three为空的记录,下面提供几种高效的实现方式:

方法一:使用Exists子查询(推荐)

这种方法直接在数据库层面完成判断,性能最优:

from django.db.models import Exists, OuterRef, Q

# 子查询:检查当前记录的同组(column_one+column_two)是否存在column_three非空的记录
has_non_null_sibling = Exists(
    Article.objects.filter(
        column_one=OuterRef('column_one'),
        column_two=OuterRef('column_two'),
        column_three__isnull=False
    )
)

# 筛选逻辑:要么自身column_three非空,要么同组没有非空记录(保留空记录)
filtered_articles = Article.objects.filter(
    Q(column_three__isnull=False) | ~has_non_null_sibling
)

方法二:通过分组统计后筛选

先统计每组(column_one+column_two)的非空记录数量,再基于结果过滤原表:

from django.db.models import Count, Q

# 统计每组的非空column_three记录数
group_stats = Article.objects.values('column_one', 'column_two').annotate(
    non_null_count=Count('column_three', filter=Q(column_three__isnull=False))
)

# 收集存在非空记录的组别
groups_with_non_null = [
    (stat['column_one'], stat['column_two'])
    for stat in group_stats if stat['non_null_count'] > 0
]

# 最终筛选:保留非空记录,或不在上述组中的空记录
filtered_articles = Article.objects.filter(
    Q(column_three__isnull=False) |
    ~Q(
        column_one__in=[g[0] for g in groups_with_non_null],
        column_two__in=[g[1] for g in groups_with_non_null]
    )
)

逻辑说明

结合你模型中的UniqueConstraint约束:

  • 同一column_one+column_two组合下,最多存在1条column_three为空的记录
  • column_three非空的记录可以有多条(只要column_three值不同)

上述两种方法都会:

  1. 保留所有column_three非空的记录
  2. 仅保留那些同组没有非空记录的column_three为空的记录

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 22:12:28