代码之家  ›  专栏  ›  技术社区  ›  alter123

如何在django列表中添加序列号?

  •  1
  • alter123  · 技术社区  · 8 年前

    我在django列表视图中使用for循环填充表。

    填充时,我想在列表中也显示序列号。

    {% for Attendee in filter.qs %} 
      {% if Attendee.checkin %}
        <tr>
          <td> Serial no. </td>
          <td>{{ Attendee.roll_no }}</td>
          <td>{{ Attendee.name }}</td>
          <td>{{ Attendee.branch }}</td>
        </tr>
        {% endif %}
    

    由于我使用过滤器来显示结果,因此无法在模型中保留序列号。

    我想要这样的东西:

    img

    我可以用什么其他方法把序列号放入列表?

    编辑:

    在列表中使用{forloop.counter}之后,序列就不连续了。 如:

    enter image description here

    3 回复  |  直到 8 年前
        1
  •  2
  •   Zags    8 年前

    你想做的就是利用 {{forloop.counter}} . 问题是计数器计算循环的所有迭代次数,而不仅仅是计算执行操作的迭代次数。

    解决方案是在将列表传递给模板之前对其进行筛选。例如:

    context={"checked_in_attendees":  [i for i in filter.qs if i.checkin], ...}
    

    然后,循环 checked_in_attendees 在模板和 {{forloop.counter} 会做你想做的。

        2
  •  0
  •   Grigoriy Mikhalkin    8 年前

    您可以通过 forloop.counter (1索引)或 forloop.counter0 (0索引)对于您的情况:

    {% for Attendee in filter.qs %} 
        {% if Attendee.checkin %}
        <tr>
            <td>{{ forloop.counter }}</td>
            <td>{{ Attendee.roll_no }}</td>
            <td>{{ Attendee.name }}</td>
            <td>{{ Attendee.branch }}</td>
        </tr>
    {% endif %}
    
        3
  •  0
  •   zhiqiang huang    8 年前

    Django模板在获取实体索引方面有自己的语法。在这里,我认为您只需要{forloop.counter}输入序列号。