访问ForeignKey直接在Django的模板中设置 [英] Access ForeignKey set directly in template in Django
本文介绍了访问ForeignKey直接在Django的模板中设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个简化的模型:
class Item(models.Model):
name = models.CharField(max_length=120)
class ItemImage(models.Model):
image = models.ImageField(upload_to='upload_dir')
item = models.ForeignKey(Item)
项目
可以有很多 ItemImages
。我还有一个模板从视图中呈现以下数据集:
An Item
can have many ItemImages
. I also have a template rendering the following data set from the view:
items = Item.objects.all()
所以现在我想在模板中做这样的事情:
So now I would want to do something like this in the template:
{% for item in items %}
<div>
{{ item.name }}<br>
<img src="{{ item.itemimage_set.all()[0] }}">
</div>
{% endfor %}
但显然这是不可能的。
But obviously that's not possible. Not from the template directly, at least.
在模板中获得相当于第一个图像的正确方法是什么?
What is the proper way to get the equivalent of the first image inside the template?
推荐答案
{% with item.itemimage_set.all|first as image %}
<img src="{{ image.url }}" />
{% endwith %}
这篇关于访问ForeignKey直接在Django的模板中设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文