【问题标题】:How do I get an iterable count on a template from a Django queryset?如何从 Django 查询集中获取模板的可迭代计数?
【发布时间】:2017-02-24 16:09:43
【问题描述】:

假设我正在使用以下代码在我的视图中获取一个查询集。

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>

基本上,我想要一个表,第一列中包含 1、2、3,第二列中包含主题名称。我该怎么做呢?

【问题讨论】:

    标签: django django-templates django-queryset


    【解决方案1】:

    我想你需要的是forloop.counter:

    {% for topic in topics %}
      <tr>
        <td>{{ forloop.counter }}</td>
        <td>{{ topic.name }}</td>
      <tr>
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 2019-02-05
      • 1970-01-01
      • 2016-11-18
      • 1970-01-01
      • 2020-06-09
      • 1970-01-01
      • 2019-09-14
      • 2016-06-23
      • 2020-09-12
      相关资源
      最近更新 更多