问题
I've three models Question, Submission, UserResult. users submit an answer to a Question, this answer is scored by the system and stored in a Submission.
The score of a user for one question is maximum amongst all of his/her submissions. This score is saved in a model called UserResult(it has three fields, a foreign key to Question, another to User and a score which is an integer)
What I want to do is to make sure when a submission is saved the related UserResult is updated. Actually it's better not to store a submission when the result is not updated. So the submission should be saved only if UserResult is updated correctly. So this whole process should be atomic. What is the proper way of handling this?
回答1:
In the Submission's save
method, call UserResult
update
method. And mark Submission's save
method as @transaction.atomic
. Then if an error happen while updating UserResult, Submission won't be saved.
来源:https://stackoverflow.com/questions/30515747/atomic-model-save-in-django