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 )
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:2 Changed 3 years ago by
|Component:||Uncategorized → Database layer (models, ORM)|
|Triage Stage:||Unreviewed → Accepted|
|Type:||Uncategorized → Cleanup/optimization|
|Version:||1.5 → master|