Opened 10 years ago

Closed 10 years ago

Last modified 10 years ago

#18021 closed Bug (invalid)

An attribute for related_name is not created for many-to-many relationships on "self"

Reported by: dmitry.blotsky@… 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


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.contains.add(b)
>>> a.contains.all()
>>> b.contains.all()
>>> b.contained_in
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'Container' object has no attribute 'contained_in'

Change History (2)

comment:1 Changed 10 years ago by Alex Ogier

Resolution: invalid
Status: newclosed

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

class Container(models.Model):
    contains = models.ManyToManyField("self", related_name="contained_in", symmetrical=False)

comment:2 Changed 10 years ago by dmitry.blotsky@…

Ah! Thank you for the clarification.

Note: See TracTickets for help on using tickets.
Back to Top