| 1 |
""" |
| 2 |
Many-to-many relationships between the same two tables |
| 3 |
|
| 4 |
In this example, a ``Person`` can have many friends, who are also ``Person`` |
| 5 |
objects. Friendship is a symmetrical relationship - if I am your friend, you |
| 6 |
are my friend. Here, ``friends`` is an example of a symmetrical |
| 7 |
``ManyToManyField``. |
| 8 |
|
| 9 |
A ``Person`` can also have many idols - but while I may idolize you, you may |
| 10 |
not think the same of me. Here, ``idols`` is an example of a non-symmetrical |
| 11 |
``ManyToManyField``. Only recursive ``ManyToManyField`` fields may be |
| 12 |
non-symmetrical, and they are symmetrical by default. |
| 13 |
|
| 14 |
This test validates that the many-to-many table is created using a mangled name |
| 15 |
if there is a name clash, and tests that symmetry is preserved where |
| 16 |
appropriate. |
| 17 |
""" |
| 18 |
|
| 19 |
from django.db import models |
| 20 |
|
| 21 |
|
| 22 |
class Person(models.Model): |
| 23 |
name = models.CharField(max_length=20) |
| 24 |
friends = models.ManyToManyField("self") |
| 25 |
colleagues = models.ManyToManyField("self", symmetrical=True, through="Colleague") |
| 26 |
idols = models.ManyToManyField("self", symmetrical=False, related_name="stalkers") |
| 27 |
|
| 28 |
def __str__(self): |
| 29 |
return self.name |
| 30 |
|
| 31 |
|
| 32 |
class Colleague(models.Model): |
| 33 |
first = models.ForeignKey(Person, models.CASCADE) |
| 34 |
second = models.ForeignKey(Person, models.CASCADE, related_name="+") |
| 35 |
first_meet = models.DateField() |