Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first item of QuerySet in template

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?

like image 491
vorpyg Avatar asked Aug 19 '10 09:08

vorpyg


3 Answers

Not any shorter, but you could use first:

{% with entry.image_set.all|first as image %}
  <img src="{{ image.get_absolute_url }}">
{% endwith %}
like image 143
Dominic Rodger Avatar answered Nov 15 '22 22:11

Dominic Rodger


Since Django 1.6 you can do

<img src="{{ entry.image_set.first.get_absolute_url }}">
like image 27
Francisco Avatar answered Nov 15 '22 22:11

Francisco


You also can do: entry.image_set.all.0 in your template.

like image 1
Yves Hary Avatar answered Nov 15 '22 22:11

Yves Hary