Get first item of QuerySet in template

Viewed 22455

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

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

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

Related