Opened 9 years ago

Closed 9 years ago

#25518 closed Cleanup/optimization (fixed)

Multiple ManyToManyField related_name documentation

Reported by: Brandon Chinn Owned by: nobody
Component: Documentation Version: 1.7
Severity: Normal Keywords: manytomanyfield multiple
Cc: Triage Stage: Ready for checkin
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I came across a bug the other day about having a model with multiple ManyToManyFields to the same Model. The bug occurs with the following code:

# models.py
class MyModel(models.Model):
    foo = models.ManyToManyField('other_app.OtherModel', related_name='+')
    bar = models.ManyToManyField('other_app.OtherModel', related_name='+')

# shell
>>> x = MyModel.objects.create()
>>> y = OtherModel.objects.create()
>>> x.foo.add(y)
>>> x.foo.all() # returns []

So there's no errors or anything thrown. However, accessing with the through model still works.

>>> x.foo.through.objects.all() # returns [<MyModel_othermodel object>]

I eventually found the answer in the Django documentation for version 1.6 saying that if you have more than one ManyToManyField pointing to the same model, you need to set the related_name to a unique value ending in +. However, this description was removed starting in the 1.7 docs. I think we need to re-add this in because it's a pretty significant specification about the ManyToManyField I would never have found, if not for a 2012 StackOverflow post.

Change History (3)

comment:1 by Tim Graham, 9 years ago

Triage Stage: UnreviewedReady for checkin
Type: UncategorizedCleanup/optimization
Version: 1.81.7

I guess 82a58ce5b67e0b79fa0efbad72e21d9d1be25ceb may have been reverted prematurely on 1.7. I think it's fixed on 1.8.5+ by 0e2d3b93043676975aa921a70b5faafef02cac5c. Does that look correct?

comment:2 by Brandon Chinn, 9 years ago

Ah yes, that works, thanks!

comment:3 by Brandon Chinn, 9 years ago

Resolution: fixed
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top