31

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?

4 Answers 4

61

Not any shorter, but you could use first:

{% with entry.image_set.all|first as image %}
  <img src="{{ image.get_absolute_url }}">
{% endwith %}
3
  • Thanks. It's slightly cleaner and "feels" better. Is there any difference computationally?
    – vorpyg
    Aug 19, 2010 at 10:09
  • 1
    @voypyg - I'd check that it doesn't actually fetch everything from the database - take a look at the SQL executed. Aug 19, 2010 at 10:25
  • It looks as both filters activate the SQL LIMIT clause.
    – vorpyg
    Aug 19, 2010 at 11:12
15

Since Django 1.6 you can do

<img src="{{ entry.image_set.first.get_absolute_url }}">
2

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

1

I was having the following queryset I just want to retrieve first element from it in jinja template.

<QuerySet [<StudentDetails: StudentDetails object (1)>, <StudentDetails: StudentDetails object (2)>]>

Solution

{{ StudentDetails.first.name }}

StudentDetails is my model

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.