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
相关产品推荐
相关产品推荐

