在 Django 的模板中直接访问设置的外键 [英] Access ForeignKey set directly in template in Django

查看:38
本文介绍了在 Django 的模板中直接访问设置的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简化的模型:

class Item(models.Model):name = models.CharField(max_length=120)类 ItemImage(models.Model):image = models.ImageField(upload_to='upload_dir')item = models.ForeignKey(Item)

一个Item 可以有多个ItemImages.我还有一个从视图中呈现以下数据集的模板:

items = Item.objects.all()

所以现在我想在模板中做这样的事情:

{% for item in items %}<div>{{ item.name }}
<img src="{{ item.itemimage_set.all()[0] }}">

{% 结束为 %}

但显然这是不可能的.至少不是直接来自模板.

获得模板中第一个图像的等价物的正确方法是什么?

解决方案

{% with item.itemimage_set.all|first as image %}<img src="{{ image.url }}"/>{% 以 %} 结尾

I have this simplified model:

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)

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 %} 

这篇关于在 Django 的模板中直接访问设置的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆