获取模板中 QuerySet 的第一项 [英] Get first item of QuerySet in template
本文介绍了获取模板中 QuerySet 的第一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的博客应用中,我想显示一个博客文章列表和与这篇文章相关的第一张图片.现在我是这样做的:
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?
推荐答案
不会更短,但你可以使用 first
:
Not any shorter, but you could use first
:
{% with entry.image_set.all|first as image %}
<img src="{{ image.get_absolute_url }}">
{% endwith %}
这篇关于获取模板中 QuerySet 的第一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文