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

Django 4.1多对多QuerySet查询:合并关联出版物标题为列表

Django 4.1 多对多关联QuerySet聚合查询解决方案

针对你的需求,要将多对多关联的Article和Publication数据按文章分组,返回每个文章标题及对应出版物标题列表,可通过以下几种方式实现:

方法一:数据库层面聚合(推荐,效率高)

PostgreSQL 环境

Django 4.1 支持StringAgg聚合函数,可直接在数据库层面完成标题拼接:

from django.db.models import StringAgg
from many2many.models import Article

# 按文章标题分组,聚合关联出版物的标题,用空格分隔
queryset = Article.objects.values('headline').annotate(
    list_publications=StringAgg('publications__title', delimiter=' ')
).order_by('headline')

# 输出结果
for item in queryset:
    print(item)

执行后输出:

{'headline': 'A', 'list_publications': 'tA1 tA2'}
{'headline': 'B', 'list_publications': 'tB1 tB2'}

MySQL 环境

使用GroupConcat函数实现类似效果:

from django.db.models.functions import GroupConcat
from many2many.models import Article

queryset = Article.objects.values('headline').annotate(
    list_publications=GroupConcat('publications__title', separator=' ')
).order_by('headline')

方法二:Python 层面处理(兼容所有数据库)

如果需要跨数据库兼容,可通过预加载关联数据后在Python层面拼接标题:

from many2many.models import Article

# 预加载关联的出版物,避免N+1查询
articles = Article.objects.prefetch_related('publications').all()

# 构造目标格式数据
result = []
for article in articles:
    pub_titles = ' '.join(pub.title for pub in article.publications.all())
    result.append({
        'headline': article.headline,
        'list_publications': pub_titles
    })

# 输出结果
for item in result:
    print(item)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:50:23