简体   繁体   English

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

[英]Get first object of query-set in Django templates

I understand that Django separates data and presentation such that Object.filter(id=value).all() isn't possible through templates.我知道 Django 将数据和表示分开,因此Object.filter(id=value).all()无法通过模板实现。

What I'm struggling to understand is the best practice for achieving this same type of end result.我正在努力理解的是实现相同类型最终结果的最佳实践。

For example, in one of my apps I've data for products, which include some one-to-many relationships with images.例如,在我的一个应用程序中,我有产品数据,其中包括与图像的一些一对多关系。 That's to say, one product may have many images.也就是说,一个产品可能有多个图片。

in my AppName/views.py file, I've got the following:在我的AppName/views.py文件中,我有以下内容:

def index(request):

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

in my AppName/templates/AppName/index.html file, there's a section with the following:在我的AppName/templates/AppName/index.html文件中,有一个部分包含以下内容:

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

What I'd like to be able to do, is include the equivalent of {{product.images.first().url}} in the mix.我希望能够做的是在混合中包含相当于{{product.images.first().url}}的内容。

What's the typical approach for this?对此的典型方法是什么?

Several options, taken from here :几个选项, 取自这里

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

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

2-Since Django 1.6ish 2-自 Django 1.6ish

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM