Django post_save preventing recursion without overriding model save()

前端 未结 9 1587
轻奢々
轻奢々 2020-11-29 23:41

There are many Stack Overflow posts about recursion using the post_save signal, to which the comments and answers are overwhelmingly: \"why not override save()\

9条回答
  •  青春惊慌失措
    2020-11-30 00:25

    Check this out...

    Each signal has it's own benefits as you can read about in the docs here but I wanted to share a couple things to keep in mind with the pre_save and post_save signals.

    • Both are called every time .save() on a model is called. In other words, if you save the model instance, the signals are sent.

    • running save() on the instance within a post_save can often create a never ending loop and therefore cause a max recursion depth exceeded error --- only if you don't use .save() correctly.

    • pre_save is great for changing just instance data because you do not have to call save() ever which eliminates the possibility for above. The reason you don't have to call save() is because a pre_save signal literally means right before being saved.

    • Signals can call other signals and or run delayed tasks (for Celery) which can be huge for usability.

    Source: https://www.codingforentrepreneurs.com/blog/post-save-vs-pre-save-vs-override-save-method/

    Regards!!

提交回复
热议问题