[英]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.