Django中相关对象向后foreignKey关系的索引(相关名称)

2024-10-04 09:18:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试索引并访问另一个表的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?

Tags: 对象namemodelobjectsmodelsa1createclass
1条回答
网友
1楼 · 发布于 2024-10-04 09:18:07

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

要访问相关的重要属性,只需在列表中的对象上使用点表示法,例如:

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

注意,因为.all()返回的是一个对象列表,所以您必须循环遍历该列表,或者像上面的示例那样选择一个。你知道吗

在模板中,它可能看起来像:

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

相关问题 更多 >