Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add() for ManyToManyField which specifies an intermediary model

There are many questions about this Exception:

AttributeError: Cannot set values on a ManyToManyField which specifies 
an intermediary model.
Use myapp.MyThroughModel's Manager instead.

The docs

You can’t just create a relationship between a Person and a Group - you need to specify all the detail for the relationship required by the Membership model. The simple add, create and assignment calls don’t provide a way to specify this extra detail. As a result, they are disabled for many-to-many relationships that use an intermediate model.

But all my attributes/columns of MyThroughModel are optional. The manager could create them.

How can I write a custom manager to automatically create MyThroughModel instances?

I need a solution at ORM-level, not Form-level.

like image 628
guettli Avatar asked Apr 09 '14 13:04

guettli


1 Answers

I found a way to tell django to ignore the extra data:

class MyThroughModel(Model):
    class Meta():
        auto_created=True
    ...

Update

This creates issues with the django internal migrations. We updated our code and don't use auto_created = True any more.

like image 122
guettli Avatar answered May 13 '23 14:05

guettli