Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reverse count a queryset in a for loop?

My template code is this

{% for announcement in announcements %}
    <tr>
        <td>{{ count }}</td>
        <td>{{ announcement.title }}</td>
        <td>{{ announcement.user.profile.name }}</td>
        <td>{{ announcement.modified }}</td>
    </tr>
{% endfor %}

I want to count down from the length of queryset to 1.

How can I do that?

like image 535
최연석 Avatar asked Dec 13 '22 23:12

최연석


1 Answers

There is a reverse counter called forloop.revcounter which counts from the length of the queryset to 1.

{% for announcement in announcements %}
    <tr>
        <td>{{ forloop.revcounter }}</td>
        <td>{{ announcement.title }}</td>
        <td>{{ announcement.user.profile.name }}</td>
        <td>{{ announcement.modified }}</td>
    </tr>
{% endfor %}

There are both zero (forloop.revcounter0) and 1 indexed (forloop.revcounter) reverse counting available.

Django template "for" documentation.

like image 96
Rafael Avatar answered Jan 12 '23 00:01

Rafael