Misleading Error: 'ManyRelatedManager' object has no attribute 'add'
|Reported by:||anonymous||Owned by:||anonymous|
|Component:||Database layer (models, ORM)||Version:||master|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||yes||Patch needs improvement:||no|
Description (last modified by charettes)
When defining a many-to-many relationship using a 'through' model, the 'add' and 'create' methods are not available, for good reason. However, rather than failing with a helpful exception directing the user to use the through model, the relevant ManyRelatedManager is simply missing its usual methods, raising a misleading AttributeError instead.
IMO, it would be more helpful, and possibly somewhat more Pythonic, to produce a type of exception that directs the user to use the through model. This correctly indicates the source of the problem, and doesn't require much additional monkeying about since the object already has to know of the need to use one as it is now, since it must be instantiated with no add/create methods.
The ManyRelatedManager is created missing two of its usual methods, raising an AttributeError if they are called. This is misleading and can result in several wasted minutes making sure the method name and object is correct, consulting documentation, and so on.
Steps to Reproduce
- Create two simple models.
- Link them with a third model defined as a 'through' relation.
- Call add or create on one of the ManyRelatedManagers.
# in models.py from django.db import models class Person(models.Model): pass class Group(models.Model): members = models.ManyToManyField(Person, through='Membership') class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) date_joined = models.DateField(auto_now_add=True)
# on shell >>> from testing.models import * >>> group = Group.objects.create() >>> person = Person.objects.create() >>> group.members.add(person) Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'ManyRelatedManager' object has no attribute 'add'}}}  See, e.g., [this StackOverflow question](http://stackoverflow.com/q/8095813/2588818) and the related top comment/answer.
Change History (7)
comment:1 Changed 16 months ago by seregon@…
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
comment:2 Changed 16 months ago by charettes
- Component changed from Uncategorized to Database layer (models, ORM)
- Description modified (diff)
- Easy pickings set
- Needs tests set
- Triage Stage changed from Unreviewed to Accepted
- Type changed from Uncategorized to Cleanup/optimization
- Version changed from 1.5 to master
comment:5 Changed 15 months ago by rkstapenhurst
- Owner changed from nobody to anonymous
- Status changed from new to assigned