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

Django中关联ManyToManyField时单DB查询实现及优化问询

问题2:单次查询获取学生姓名与科目数量

用annotate结合Count聚合函数即可实现,一次查询拿到两个数据:

from django.db.models import Count

student_data = Student.objects.filter(pk=student_id).annotate(
    subject_count=Count('subjects')
).values('name', 'subject_count').first()

if student_data:
    print(student_data['name'])
    print(student_data['subject_count'])

原理

Count('subjects')会在查询学生时,自动左连接多对多关联表,聚合出该学生的科目总数,整个过程由数据库一次性完成,避免了原方案中student.subjects.count()触发的第二次查询。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 04:35:20