guettli
guettli

Reputation: 27825

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.

Upvotes: 7

Views: 5094

Answers (1)

guettli
guettli

Reputation: 27825

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.

Upvotes: 7

Related Questions