when to use pre_save, save, post_save in django?

前端 未结 3 2178
南笙
南笙 2020-12-13 19:04

I see I can override or define pre_save, save, post_save to do what I want when a model instance gets saved.

Which one is preferred in which situation

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-13 19:27

    Don't forget about recursions risk. If you use post_save method with instance.save() calling, instead of .update method, you should disconnect your post_save signal:

    Signal.disconnect(receiver=None, sender=None, dispatch_uid=None)[source] To disconnect a receiver from a signal, call Signal.disconnect(). The arguments are as described in Signal.connect(). The method returns True if a receiver was disconnected and False if not.

    The receiver argument indicates the registered receiver to disconnect. It may be None if dispatch_uid is used to identify the receiver.

    ... and connect it again after.

    update() method don't send pre_ and post_ signals, keep it in mind.

提交回复
热议问题