Get first item of QuerySet in template

爱⌒轻易说出口 提交于 2019-12-30 03:47:12

问题


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:


Not any shorter, but you could use first:

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



回答2:


Since Django 1.6 you can do

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


来源:https://stackoverflow.com/questions/3520554/get-first-item-of-queryset-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!