Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django中相关对象向后外键关系的索引(相关名称)_Python_Django_Django Models - Fatal编程技术网

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

Python Django中相关对象向后外键关系的索引(相关名称),python,django,django-models,Python,Django,Django Models,我试图索引到另一个表的foreignkey中引用的相关对象并从中访问属性: class table1 (models.Model): name = models.CharField() .... class table2 (models.Model): attr1 = models.ForeignKey(table1, related_name = "backTable") importantAttribute = models.Charfield() 我想从

我试图索引到另一个表的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?
>>t1=table1.objects.create(name=“t1”)
>>>a1=表2.objects.create(name=“a1”,attr1=t1)
>>>t1.backTable.all()
>>> []
>>>>我想从这里t1访问表2的ImportAttribute。怎样?

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

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

t1.backTable.all()[0].importantAttribute
请注意,由于
.all()
返回的是一个对象列表,因此必须循环遍历该列表,或者像上面的示例那样选择一个对象

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

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