views:

33

answers:

1

In my blog app I want to display a list of blog posts and the first image connected to this post. Now I do it this way:

{% for image in entry.image_set.all|slice:"1" %}
    <img src="{{ image.get_absolute_url }}">
{% endfor %}

Is there a template shortcut I don't know about, or maybe I should just write my own Manager?

+1  A: 

Not any shorter, but you could use first:

{% with entry.image_set.all|first as image %}
  <img src="{{ image.get_absolute_url }}">
{% endwith %}
Dominic Rodger
Thanks. It's slightly cleaner and "feels" better. Is there any difference computationally?
vorpyg
@voypyg - I'd check that it doesn't actually fetch everything from the database - take a look at the SQL executed.
Dominic Rodger
It looks as both filters activate the SQL LIMIT clause.
vorpyg
@vorpyg - excellent, go Django's ORM!
Dominic Rodger