开发者

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="{{ 开发者_JAVA技巧image.get_absolute_url }}">
{% endfor %}

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


Not any shorter, but you could use first:

{% with entry.image_set.all|first as image %}
  <img src="{{ image.get_absolute_url }}">
{% endwith %}


Since Django 1.6 you can do

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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜