Atomic post_save operation

19 views
Skip to first unread message

Clara Daia

unread,
May 27, 2019, 11:08:19 AM5/27/19
to Django users
Hello, guys

tl; dr:
Is there a way to make [save + post_save] and [delete + post_delete] operations atomic? That is, if the operations in the function triggered by the post_save signal fail, then the save itself is reverted?

Long version:
I have a certain model MyModel and I keep track of changes in a certain field MyModel.my_field with another model, let's call it MyFieldHistory. I create a new MyFieldHistory item if the field changes in the main model, but I must also be able to change the history of an object in case mistakes are made, and if history changes and the latest element is different from the current value, I update the MyModel object. That creates a bit of a loop in which a change in MyModel triggers a change in MyFieldHistory, which is turns triggers a change in MyModel.

I am currently doing this in a assymetrical way:
MyModel.save() has been customized to check whether the field history latest item is the same as the current value in the model. If not, it creates a new item in the history, with the current datetime and MyModel.my_field value. I made it atomic to make sure the update fails if for any reason the history item cannot be created.

I created a function which also checks whether the field history latest item is the same as the current value in the model, but enforces the history data over the MyModel instance - that is, if they differ, the MyModel instance is changed rather than the history. I made it with a function so that I can use it both with post_save and post_delete signals, but I would like to make sure that if this function fails, the change in the history will be reverted, almost like an integrity guarantee.

Is that possible? Or should I be doing this some other way?
Reply all
Reply to author
Forward
0 new messages