[英]Get first object of query-set in Django templates
我知道 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-(一种较旧的方法):
{% 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 }}">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.