Django多对多关联查询:统计每个Profession关联的Account账户数量
实现方案
步骤1:导入聚合函数
from django.db.models import Count
步骤2:构造查询语句
直接对Profession模型做带聚合的查询即可,Django ORM会自动处理多对多关联的统计逻辑:
# 每个返回的Profession实例会新增account_count属性,存储关联的Account总数 profession_list = Profession.objects.annotate(account_count=Count('account')).all()
说明:如果你的Account模型中多对多字段设置了
related_name参数,需要把Count里的account替换成你自定义的related_name值。比如你设置profession = models.ManyToManyField(Profession, related_name='accounts'),那么查询语句就改为Count('accounts')
步骤3:渲染使用示例
视图层代码示例
from django.shortcuts import render from django.db.models import Count from .models import Profession def get_profession_statistics(request): professions = Profession.objects.annotate(account_count=Count('account')) return render(request, 'profession_stat.html', {"professions": professions})
模板层遍历示例
<table> <thead> <tr> <th>职业名称</th> <th>关联账户总数</th> </tr> </thead> <tbody> {% for item in professions %} <tr> <td>{{ item.profession }}</td> <td>{{ item.account_count }}</td> </tr> {% endfor %} </tbody> </table>
可选扩展
如果只需要查询关联账户数大于0的职业,可以在查询后加过滤条件:
profession_list = Profession.objects.annotate(account_count=Count('account')).filter(account_count__gt=0)
内容的提问来源于stack exchange,提问作者omarsenoussaoui
相关产品推荐
相关产品推荐

