1 """ |
|
2 12. Relating a model to another model more than once |
|
3 |
|
4 In this example, a ``Person`` can have a ``mother`` and ``father`` -- both of |
|
5 which are other ``Person`` objects. |
|
6 |
|
7 Set ``related_name`` to designate what the reverse relationship is called. |
|
8 """ |
|
9 |
|
10 from django.db import models |
|
11 |
|
12 class Person(models.Model): |
|
13 full_name = models.CharField(maxlength=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') |
|
16 |
|
17 def __str__(self): |
|
18 return self.full_name |
|
19 |
|
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) |
|
23 >>> dad.save() |
|
24 >>> mom = Person(full_name='Jane Smith', mother=None, father=None) |
|
25 >>> mom.save() |
|
26 |
|
27 # Give mom and dad a kid. |
|
28 >>> kid = Person(full_name='John Smith Junior', mother=mom, father=dad) |
|
29 >>> kid.save() |
|
30 |
|
31 >>> kid.mother |
|
32 <Person: Jane Smith> |
|
33 >>> kid.father |
|
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() |
|
40 [] |
|
41 >>> kid.fathers_child_set.all() |
|
42 [] |
|
43 """} |
|