如何从 Django 查询集中获取模板的可迭代计数?
How do I get an iterable count on a template from a Django queryset?
假设我正在使用以下代码在我的视图中获取一个查询集。
topics = Topic.objects.all()[:3]
在我的模板中,我这样做:
<table>
<tr>
<td>#</td>
<td>Name</td>
<tr>
{% for topic in topics %}
<tr>
<td>{{ topic.count }}</td>
<td>{{ topic.name }}</td>
<tr>
{% endfor %}
</table>
基本上,我想要一个 table,第一列为 1、2、3,第二列为主题名称。我该怎么做呢?
我想你需要的是forloop.counter
:
{% for topic in topics %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ topic.name }}</td>
<tr>
{% endfor %}
假设我正在使用以下代码在我的视图中获取一个查询集。
topics = Topic.objects.all()[:3]
在我的模板中,我这样做:
<table>
<tr>
<td>#</td>
<td>Name</td>
<tr>
{% for topic in topics %}
<tr>
<td>{{ topic.count }}</td>
<td>{{ topic.name }}</td>
<tr>
{% endfor %}
</table>
基本上,我想要一个 table,第一列为 1、2、3,第二列为主题名称。我该怎么做呢?
我想你需要的是forloop.counter
:
{% for topic in topics %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ topic.name }}</td>
<tr>
{% endfor %}