About creating related objects dynamically on object save
Oct 31, 2013 · Updated: Jul 12, 2021 · by Tim Kamanin
When you save your main object and want to attach / create / modify attached to it related models you need to remember the following:
-
Do this in post_save signal, because related objects need pk and you get pk in post_save (when you create a new object);
-
If you manipulate ForeignKey or OneToOneField in post_save(), no additional moves needed. Manipulate there, don't forget to save() objects after the manipulation. For example:
main.related.save(); -
If you manipulate ManyToMany, you may do this in
post_saveas well, but if you use admin, make sure you call same logic in admin formsave_relatedmethod, details in my previous post.
Hey, if you've found this useful, please share the post to help other folks find it: