Tom Brock
Tom Brock

Reputation: 950

Why doesn't save() automatically call save_m2m()?

I understand if I do something like object.save(commit=False), my m2m relationships won't automatically get saved, but if I then later call object.save() I am forced to also call self.save_m2m().

Since I am calling save() I don't understand why I need to manually call save_m2m() too.

Can someone explain the logic behind this?

Thank you.

Upvotes: 0

Views: 320

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

The documentation does explain this.

form.save() includes the creation and saving of M2M relations; this is because the form can do the whole thing in one go. But as soon as you use commit=False, the form can no longer create the M2M relations, because the object itself has not been saved; an M2M is impossible without an ID to link to.

object.save() can’t call save_m2m, because that is an action of the form, not the model instance object. The object doesn’t even know about the m2m relations at this point, because the form couldn’t create them. That’s why you need to call the save_m2m method of the form.

Upvotes: 1

Related Questions