我正在尝试索引并访问另一个表的foreignkey中引用的相关对象的属性:
class table1 (models.Model):
name = models.CharField()
....
class table2 (models.Model):
attr1 = models.ForeignKey(table1, related_name = "backTable")
importantAttribute = models.Charfield()
我想从Python API解释器访问表2中的importAttribute:
>>> 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对象的列表。你知道吗要访问相关的重要属性,只需在列表中的对象上使用点表示法,例如:
注意,因为
.all()
返回的是一个对象列表,所以您必须循环遍历该列表,或者像上面的示例那样选择一个。你知道吗在模板中,它可能看起来像:
相关问题 更多 >
编程相关推荐