如何只获取模板中的第一个对象?

时间:2013-02-22 12:44:02

标签: python django

的观点:

....
d = Data.objects.filter(is_accepted=True)
....

模板:

{% for item in d %}
    {% for picture in item.photo_set.all %}
        <img class="image" src="{{ picture.photo.url}}">
    {% endfor %}
{% endfor %}

如何只获得第一张照片? ({{ picture.photo.url}}

3 个答案:

答案 0 :(得分:3)

您可以使用点符号进行索引:

{{ item.photo_set.all.0.photo.url }}

答案 1 :(得分:1)

您需要使用forloop.first。看看docs

{% for item in d %}
    {% for picture in item.photo_set.all %}
        {% if forloop.first %}
            <img class="image" src="{{ picture.photo.url}}">
        {% endif %}
    {% endfor %}
{% endfor %}

答案 2 :(得分:1)

首先,一把锋利的刀。

其次,slice

相关问题