You need to enable JavaScript to run this app. Django多关联表过滤后如何在模板中渲染设备汇总统计表格
优惠活动
大模型
产品
解决方案
定价
更多

Django多关联表过滤后如何在模板中渲染设备汇总统计表格

解决方案

推荐直接在视图层完成所有统计逻辑,一次性把需要的聚合数据传给模板,避免模板中做复杂查询引发N+1性能问题,具体实现步骤如下:

1. 视图层修改(views.py)

首先导入Django ORM所需的聚合工具,使用annotate给每个地点对象附加对应类型设备的统计字段:

# 顶部导入依赖
from django.db.models import Count, Case, When, IntegerField

# 视图逻辑部分修改
def your_view(request):
    locations = Location.objects.annotate(
        # 统计通信设备数量
        comms_equip_count = Count(
            Case(
                When(rack__equipment__type="Comms equip", then=1),
                default=0,
                output_field=IntegerField()
            )
        ),
        # 统计处理设备数量
        processing_equip_count = Count(
            Case(
                When(rack__equipment__type="Processing equip", then=1),
                default=0,
                output_field=IntegerField()
            )
        )
    )
    context = {'locations': locations}
    return render(request, 'appname/summary.html', context)

说明:rack__equipment__type是Django ORM的跨外键关联查询语法,两层外键分别用双下划线连接即可。如果后续需要新增其他设备类型的统计,只需在annotate中追加对应规则即可,注意When条件中的type值要和Equipment表中存储的type字段值完全一致。

2. 模板层修改(summary.html)

直接遍历视图传过来的locations对象,直接读取附加的统计字段渲染表格即可:

<table border="1" cellpadding="8" cellspacing="0">
  <thead>
    <tr>
      <th>Location</th>
      <th>Comms Equip</th>
      <th>Processing Equip</th>
    </tr>
  </thead>
  <tbody>
    {% for loc in locations %}
    <tr>
      <td>{{ loc.location_name }}</td>
      <td>{{ loc.comms_equip_count }}</td>
      <td>{{ loc.processing_equip_count }}</td>
    </tr>
    {% endfor %}
  </tbody>
</table>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 00:33:04