DjangoDjango

About creating related objects dynamically on object save

Oct 31, 2013 · Updated: Nov 04, 2017 · 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:

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.

Hey, if you've found this useful, please share the post to help other folks find it:

There's even more:

Subscribe for updates

  • via Twitter: @timonweb
  • old school RSS:
  • or evergreen email ↓ ↓ ↓