在Django模板中获取查询集的第一个对象

时间:2017-12-24 00:44:28

标签: python django django-templates django-template-filters

据我所知,Django将数据和表示分开,因此Object.filter(id=value).all()无法通过模板实现。

我努力理解的是实现这种相同类型的最终结果的最佳实践。

例如,在我的某个应用中,我提供了产品数据,其中包括与图片的一对多关系。可以说,一种产品可能有很多图像。

在我的AppName/views.py文件中,我有以下内容:

def index(request):

    response = render_to_response('AppName/index.html', context={
        'products': Product.objects.all(),
    })
    return response

在我的AppName/templates/AppName/index.html文件中,其中包含以下内容:

{% for product in products %}
    <li>{{ product.name }}: ${{ product.price }}</li>
{% endfor %}

我希望能够做的是,在混合中包含相当于{{product.images.first().url}}的内容。

这是什么典型方法?

1 个答案:

答案 0 :(得分:0)

几个选项,taken from here

1-(一种较旧的方法):

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

2-自Django 1.6ish起

<img src="{{ entry.image_set.first.get_absolute_url }}">
相关问题