2
12. Relating a model to another model more than once
4
In this example, a ``Person`` can have a ``mother`` and ``father`` -- both of
5
which are other ``Person`` objects.
7
Set ``related_name`` to designate what the reverse relationship is called.
10
from django.db import models
12
class Person(models.Model):
13
full_name = models.CharField(max_length=20)
14
mother = models.ForeignKey('self', null=True, related_name='mothers_child_set')
15
father = models.ForeignKey('self', null=True, related_name='fathers_child_set')
17
def __unicode__(self):
20
__test__ = {'API_TESTS':"""
21
# Create two Person objects -- the mom and dad in our family.
22
>>> dad = Person(full_name='John Smith Senior', mother=None, father=None)
24
>>> mom = Person(full_name='Jane Smith', mother=None, father=None)
27
# Give mom and dad a kid.
28
>>> kid = Person(full_name='John Smith Junior', mother=mom, father=dad)
34
<Person: John Smith Senior>
35
>>> dad.fathers_child_set.all()
36
[<Person: John Smith Junior>]
37
>>> mom.mothers_child_set.all()
38
[<Person: John Smith Junior>]
39
>>> kid.mothers_child_set.all()
41
>>> kid.fathers_child_set.all()