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

Django模板嵌套for循环如何获取全局累计总迭代次数

实现嵌套循环全局累计计数的两种方案

方案1:视图层预处理(最推荐)

Django设计理念不推荐在模板中处理复杂计算,直接在视图给每条数据加上全局序号即可:

# 视图代码
cities = [
    {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
    {'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
    {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
    {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
    {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
]
# 遍历给每条数据添加全局序号
for idx, city in enumerate(cities, start=1):
    city['global_idx'] = idx
# 把cities传到模板即可

模板代码直接调用预存的序号:

{% regroup cities by country as country_list %}

{% for country, local_cities in country_list %}
    {{ country }}
    {% for city in local_cities %}
       {{ city.global_idx }}){{ city.name }}: {{ city.population }}
    {% endfor %}
{% endfor %}

方案2:模板层自定义标签实现

如果不方便修改视图,可以自定义累加标签实现计数:

  1. 先在你的APP下新建templatetags目录,添加counter_tags.py文件:
from django import template
register = template.Library()

@register.simple_tag
def add_counter(counter):
    return counter + 1
  1. 模板中使用自定义标签维护计数器:
{% load counter_tags %}
{% with total_counter=0 %}
{% regroup cities by country as country_list %}

{% for country, local_cities in country_list %}
    {{ country }}
    {% for city in local_cities %}
        {% add_counter total_counter as total_counter %}
        {{ total_counter }}){{ city.name }}: {{ city.population }}
    {% endfor %}
{% endfor %}
{% endwith %}

两种方案都可以实现目标输出效果,优先选方案1,性能更高逻辑更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:57:03