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

如何不使用prefetch,通过Django ORM单查询获取MySQL反向外键数据

Django ORM单查询实现关联数据嵌套输出方案

实现代码

首先导入需要的ORM工具函数:

from django.db.models import F, Q
from django.db.models.aggregates import ArrayAgg
from django.db.models.functions import JSONObject

执行查询:

# PostgreSQL 环境使用 ArrayAgg
result = User.objects.annotate(
    emails=ArrayAgg(
        JSONObject(
            id=F('emails__id'),
            email=F('emails__email')
        ),
        distinct=True,
        # 注释掉下方filter则保留无邮箱的用户,emails返回空数组
        filter=~Q(emails__id=None)
    )
).values('id', 'fname', 'emails')

如果你使用MySQL 8.0+,将ArrayAgg替换为JSONArrayAgg即可,其余逻辑一致。

效果说明

上述查询生成的是单条SQL语句,没有使用任何prefetch相关功能,返回的result直接就是你要求的嵌套结构字典列表,无需额外手动组装数据。

内容的提问来源于stack exchange,提问作者Sabish.M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 04:33:02