Django模板.整数迭代的最佳方式



我想在一个html中显示尽可能多的表格,因为在锦标赛对象中有循环。

我需要在Tournament模型的loop_count字段中按值迭代(列表中的数字本身不需要)。我在网上找不到方法,所以我自己想出来的。使用属性,这是最好的方法吗?

锦标赛模型:

class Tournament(models.Model):
name = models.CharField("Title",max_length=50,unique=True)
loop_count = models.PositiveSmallIntegerField("Count of loop")
@property
def loop_count_list(self):
return range(self.loop_count)

Html:

{% for loop in tournament.loop_count_list %}
<div class="home-champ"...>
{% endfor %>

如果我需要列表中的数字本身,我可以做以下操作:(我知道关于forloop.counter)

Html:

{% for loop in tournament.loop_count_list %}
<b>Index: {{ loop }}</b>
<div class="home-champ"...>
{% endfor %>

如果这对你有用,我就这么做。

你可以写一个自定义标签来完成几乎相同的事情。

这里也有一个hack(但聪明)的方法:https://stackoverflow.com/a/14389078/4872140

关于"最佳"方法的问题是棘手和不鼓励的。

最新更新