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

如何在Django ORM的values()查询结果中获取已annotate的关联s_id字段

问题原因

你在SectionStudent查询集上通过annotate定义的s_id字段,仅作用于当前SectionStudent查询集。后续调用.qouta.feeqouta_set.all()时,已经切换到了FeeQouta的独立查询集,之前的注解字段无法跨查询集传递,因此不会出现在最终values()的返回结果中。

解决方案

方案1:直接从FeeQouta发起查询(推荐)

通过反向关联路径打通所有过滤条件,直接在FeeQouta查询集上添加s_id注解:

from django.db.models import F

result = FeeQouta.objects.filter(
    qouta__sectionstudent__section__feesection__id=1,
    qouta__sectionstudent__student__id=1
).annotate(
    s_id=F('qouta__sectionstudent__student__id')
).values()

该查询返回的结果会直接包含s_id字段,完全符合你的预期。

方案2:原有链式调用手动补全字段

如果你不想调整原有查询结构,可以先取出固定的s_id值,再手动写入FeeQouta的查询结果中:

# 先获取目标s_id
s_id = 1  # 你查询条件里已经固定了student__id=1,也可以动态查询获取
# 执行原有查询拿到结果列表
fee_qouta_list = list(FeeSection.objects.get(id=1).section.sectionstudent_set.get(student__id=1).qouta.feeqouta_set.all().values())
# 给每个条目补s_id字段
for item in fee_qouta_list:
    item['s_id'] = s_id

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:00:05