2006-05-02 01:31:56 +00:00
|
|
|
"""
|
2014-09-24 05:13:13 +00:00
|
|
|
Many-to-many relationships between the same two tables
|
2006-05-02 01:31:56 +00:00
|
|
|
|
2008-08-12 14:15:38 +00:00
|
|
|
In this example, a ``Person`` can have many friends, who are also ``Person``
|
|
|
|
objects. Friendship is a symmetrical relationship - if I am your friend, you
|
|
|
|
are my friend. Here, ``friends`` is an example of a symmetrical
|
|
|
|
``ManyToManyField``.
|
2006-05-02 01:31:56 +00:00
|
|
|
|
2008-08-12 14:15:38 +00:00
|
|
|
A ``Person`` can also have many idols - but while I may idolize you, you may
|
|
|
|
not think the same of me. Here, ``idols`` is an example of a non-symmetrical
|
|
|
|
``ManyToManyField``. Only recursive ``ManyToManyField`` fields may be
|
|
|
|
non-symmetrical, and they are symmetrical by default.
|
2006-05-02 01:31:56 +00:00
|
|
|
|
2008-08-12 14:15:38 +00:00
|
|
|
This test validates that the many-to-many table is created using a mangled name
|
|
|
|
if there is a name clash, and tests that symmetry is preserved where
|
|
|
|
appropriate.
|
2006-05-02 01:31:56 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
from django.db import models
|
|
|
|
|
2010-10-09 16:26:48 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
class Person(models.Model):
|
2007-08-05 05:14:46 +00:00
|
|
|
name = models.CharField(max_length=20)
|
2006-05-02 01:31:56 +00:00
|
|
|
friends = models.ManyToManyField('self')
|
2019-04-19 16:12:04 +00:00
|
|
|
colleagues = models.ManyToManyField('self', symmetrical=True, through='Colleague')
|
2006-05-02 01:31:56 +00:00
|
|
|
idols = models.ManyToManyField('self', symmetrical=False, related_name='stalkers')
|
|
|
|
|
2012-08-12 10:32:08 +00:00
|
|
|
def __str__(self):
|
2006-05-02 01:31:56 +00:00
|
|
|
return self.name
|
2019-04-19 16:12:04 +00:00
|
|
|
|
|
|
|
|
|
|
|
class Colleague(models.Model):
|
|
|
|
first = models.ForeignKey(Person, models.CASCADE)
|
|
|
|
second = models.ForeignKey(Person, models.CASCADE, related_name='+')
|
|
|
|
first_meet = models.DateField()
|