在Django中使用ForeignKey从模型中获取信息

时间:2012-08-23 04:53:14

标签: django

我仍然掌握着Django。例如,您有两个模型,其中一个使用ForeignKey与另一个相关。

class Parent(models.Model):
   name = models.CharField(max_length=255)
   birthday= models.DateField(blank=True,null=True)

class Child(models.Model):
   name = models.CharField(max_length=255)
   parent= models.ForeignKey(Parent)

在上面的示例中,我想访问特定的孩子并获取他的名字。我想通过父实例来完成它。所以,例如,我有一个叫做约翰的父母,我想知道他孩子的名字。我该怎么做?

如果这是一个简单的问题,请原谅我......

2 个答案:

答案 0 :(得分:4)

以下代码解决了您的问题。请注意,child_set是相关经理的默认名称。有关详细信息,请参阅https://docs.djangoproject.com/en/dev/ref/models/relations/

john = Parent.objects.get(name='John')
johns_children = john.child_set.all()
# Print names of his children
for child in johns_children:
    print child.name
# Get child named Jack
jack = john.child_set.get(name='jack')
# Filter children by gender
jack = john.child_set.filter(gender='F')
...

答案 1 :(得分:1)

给定一个父对象parent = Parent.objects.get(name='John'),您可以使用children = Child.objects.filter(parent=parent_id)来获取他的孩子,然后在任何返回的对象上调用.name

for child in children:
    print child.name