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

如何使用Django ORM二次过滤查询集,筛选指定当前状态的应用

Django ORM 实现查询当前状态为指定值的应用

解法1:基于现有DISTINCT查询扩展(仅PostgreSQL兼容)

该写法完全贴合你现有的查询逻辑,生成的SQL和你给出的原生SQL逻辑完全一致:

# 1. 原有获取每个应用最新状态的查询逻辑
current_statuses = TrackApplicationStatus.objects.order_by(
    'application_id', '-created_at'
).distinct('application_id')

# 2. 追加状态过滤条件,获取符合要求的应用ID
target_status_id = 3
matched_app_ids = current_statuses.filter(
    status_id=target_status_id
).values_list('application_id', flat=True)

# 3. 如需获取完整的Application实例,追加查询即可
matched_applications = Application.objects.filter(id__in=matched_app_ids)

解法2:通用子查询注解方式(兼容所有Django支持的数据库)

如果需要经常查询应用的当前状态,或者你使用的是非PostgreSQL数据库,可以用子查询注解的方式实现:

from django.db.models import Subquery, OuterRef

# 构造子查询:查询指定Application对应的最新状态ID
latest_status_subquery = TrackApplicationStatus.objects.filter(
    application=OuterRef('pk')
).order_by('-created_at').values('status_id')[:1]

# 给Application查询集注解当前状态,直接过滤出符合要求的应用
target_status_id = 3
matched_applications = Application.objects.annotate(
    current_status_id=Subquery(latest_status_subquery)
).filter(current_status_id=target_status_id)

注意事项

  • 解法1中使用的distinct(*fields)语法是PostgreSQL数据库独有的特性,MySQL、SQLite等数据库不支持该用法。
  • 两种实现的执行效率基本一致,最终都只会生成一次关联查询,不会出现N+1问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 18:57:04