Django Many to Many Model Saving with Intermediary (Through) Model

I spent more time than I wanted to pulling together the solution for saving a child and its relation to its parent at the same time, while setting a value on the many-to-many model in between.

It feels like a pretty typical pattern, but the documentation and the info I found all over never quite got me there.

There seems to be a feeling that using inlines for this is the right idea…and I mostly agree. However, the inline stuff was really aimed at having lots of sub-forms, and submitting two forms separately. In this case I need to do them all together. So, I pulled the two crucial fields off of the many-to-many model, and added them ‘manually’ to a ModelForm for the child model.

A little magic in the ‘save()’ method for the form, and voila!

The gists of the related bits are below:

Comments are closed.