繁体   English   中英

Django中相关对象向后的ForeignKey关系的索引(related_name)

[英]Index from related object backward foreignKey relation in Django (related_name)

我试图索引并访问另一个表的外键中引用的相关对象的属性:

class table1 (models.Model):
    name =  models.CharField()
    ....
class table2 (models.Model):
    attr1 = models.ForeignKey(table1, related_name = "backTable")
    importantAttribute = models.Charfield()

我想从Python API解释器从table2访问ImportantAttribute:

 >>> t1 = table1.objects.create(name="t1")
 >>> a1 = table2.objects.create(name="a1", attr1 = t1)
 >>> t1.backTable.all() 
 >>> [<table2: a1>]
 >>>> I'd like to access importantAttribute of table2 from t1 here. how?

ForeignKey字段创建多对一关系,因此t1.backTable.all()将返回table2对象的列表。

要访问相关的重要属性,您可以在列表中的对象上使用点符号,例如:

t1.backTable.all()[0].importantAttribute

请注意,由于.all()返回的是对象列表,因此您必须遍历该列表或像上面的示例一样选择一个对象。

在模板中,它可能类似于:

{% for backTable in t1.backTable.all %}
    {{ backTable.importantAttribute }}
{% endfor %}

暂无
暂无

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

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