#18021 closed Bug (invalid)
An attribute for related_name is not created for many-to-many relationships on "self"
Reported by: | Owned by: | nobody | |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 1.3 |
Severity: | Normal | Keywords: | many-to-many many to many reverse lookup relationship related_name related name recursive self |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
When a ManyToMany relationship named "a1" is specified on "self" with a related_name="a2", an attribute named "a2" is NOT created on the object and reverse relationships are updated in related objects' "a1" attribute.
Code to demonstrate:
class Container(models.Model): contains = models.ManyToManyField("self", related_name="contained_in") (Interactive Console) >>> a, b = Container(), Container() >>> a.save() >>> b.save() >>> a.contains.add(b) >>> a.contains.all() [b] >>> b.contains.all() [a] >>> b.contained_in Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'Container' object has no attribute 'contained_in'
Note:
See TracTickets
for help on using tickets.
This is expected behavior. When you have a many-to-many relation, the relationship is considered symmetric and the reverse attribute is not created, unless you explicitly set
symmetrical=False
. See https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField.symmetrical