Opened 12 years ago

Closed 12 years ago

Last modified 12 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

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'

Change History (2)

comment:1 by Alex Ogier, 12 years ago

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 https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField.symmetrical

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

comment:2 by dmitry.blotsky@…, 12 years ago

Ah! Thank you for the clarification.

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