我已经阅读了所有其他答案,其中一些人说你可以,有些人说你不能这样我试过。我尝试做的是迭代我的数组,如果对象的id匹配,则递增计数器并稍后显示。我把它设置成这样:
{% with elect_count=1 %}
{% for device in devices %}
{% if device.ixDeviceType.ixDeviceClass_id == 3 %}
{{ elect_count|add:1 }}//increment the counter
{% endif %}
{% endfor %}
<li style="list-style: none;" class="padding5">
<span class="glyphicon glyphicon-flash" style="color: yellow; font-size: larger;"></span>
<span name="meter-count">{{ elect_count }}</span>//display total number of elect_count
<ul id="meter-summary">
</ul>
</li>
{% endwith %}
但是当我运行此功能时,会显示1 1 1 1
而不是递增此elect_count变量,当我执行{{ elect_count }}
时,它会显示{0}
答案 0 :(得分:1)
您无法在模板中保存计数器,但您可以在视图中执行此操作并将其传递到上下文中:
views.py
def view_function(request):
elect_count = 0
for device in devices:
if device.ixDeviceType.ixDeviceClass_id == 3:
elect_count += 1
context['elect_count'] = elect_count