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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With