About creating related objects dynamically on object save

31 Oct · by Tim Kamanin · 1 min read

When you save your main object and want to attach / create / modify attached to it related models you need to remember the following:

1) Do this in post_save signal, because related objects need pk and you get pk in post_save (when you create a new object)

2) 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()

3) If you manipulate ManyToMany, you may do this in post_save() as well, but if you use admin, make sure you call same logic in admin form save_related() method, details in my previous post.

Comments

Required for comment verification