Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a for loop in a Django template and then slice the result

In a Django template, I'm iterating over a set of photos, and displaying them one by one. Specifically, right now I just have one photo set, containing 6 objects. I display these 6 objects like so:

{% for pic in picstream.photo_set.all reversed %}
    <img src="{{ pic.image_file.url }}"></img>
{% endfor %}

Adding reversed to the statement gives me the 6 objects in the desired ordering (i.e. the latest ids first).

Next, I want to display not more than 4 objects from the photo_set. I added |slice:":4" to picstream.photo_set.all to achieve this. Problem is, it's cutting off the first two objects from my desired oredering.

It seems there ought to have been a way to reverse the list first, and slice later? Need a simple way to do this, without performance compromises.

like image 855
Hassan Baig Avatar asked Feb 08 '23 03:02

Hassan Baig


1 Answers

Instead of using the reversed argument for the for template tag, you can use the reverse method of the queryset itself:

{% for pic in picstream.photo_set.all.reverse|slice:":4" %}
    <img src="{{ pic.image_file.url }}"></img>
{% endfor %}

If you are evaluating the original (non-reversed) queryset somewhere else in your code then this will result in a second query hitting the database. If this is the case then you are better off moving the logic into your view code itself or into a template tag.

like image 159
solarissmoke Avatar answered May 26 '23 16:05

solarissmoke