lakshmen
lakshmen

Reputation: 29064

Getting an information from the model that is related using ForeignKey in Django

I am still getting the hang of Django. For example, you have two models and one of them is related to the other using 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)

In the example above, i would like to access the particular child and get his name. I will like to do it through the parent instance. So for example, i have a Parent called John and i would like to know his child's name. How do i do it?

Please pardon me if it is a simple question...

Upvotes: 1

Views: 306

Answers (2)

shanyu
shanyu

Reputation: 9716

The below code addresses your question. Note that child_set is the related manager's default name. For more information, see 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')
...

Upvotes: 4

K Z
K Z

Reputation: 30453

Given a parent object parent = Parent.objects.get(name='John'), you can get his children by using children = Child.objects.filter(parent=parent_id), then it is a matter of calling .name on any of the returned objects:

for child in children:
    print child.name

Upvotes: 1

Related Questions