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

Django多对多关联统计:Thing对应Label的数量统计问题

解决Thing对应Label的关联次数统计问题

视图层(views.py)实现

通过正确的ORM查询获取目标Thing对应的各Label关联次数:

from django.db.models import Count
from .models import Thing, Label

def thing_detail(request, thing_pk):
    # 获取目标Thing对象
    thing = Thing.objects.get(pk=thing_pk)
    # 统计该Thing对应的每个Label的关联次数
    label_counts = Label.objects.filter(
        description__thingname=thing  # 过滤关联到当前Thing的Label
    ).annotate(
        count=Count('description')  # 统计每个Label被多少个Description关联
    ).order_by('-count')  # 按次数降序排列,可选
    
    context = {
        'thing': thing,
        'label_counts': label_counts
    }
    return render(request, 'thing_detail.html', context)

关键说明

  • 你原查询的问题在于未正确建立Label与目标Thing的关联过滤,需通过description__thingname反向关联到Thing,而非使用不存在的description_form字段。
  • Count('description')统计的是每个Label被关联的Description数量,即用户提交表单时该Label被选中的次数。

模板层(thing_detail.html)渲染

在模板中遍历统计结果,输出每个Label的名称和次数:

<h1>{{ thing.name }}的标签统计</h1>
<ul>
    {% for label in label_counts %}
        <li>{{ label.name }}: {{ label.count }}</li>
    {% empty %}
        <li>暂无标签统计数据</li>
    {% endfor %}
</ul>

针对“猫”这类Thing,会输出类似格式的结果:

  • fluffy: 10
  • fuzzy: 6

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 15:00:43