Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django transaction management

I have a django project in which database values need to be updated fairly often on their own. There's a cronjob that runs to update these values in the database, but some of the operations require atomic transactions. Does anybody know how to make a model method be a complete transaction in django without going through views?

Ideally, I'd like to be able to start a transaction at the beginning of a method and commit it at the end, and then just be able to call that method from anywhere (a view or a cronjob) with the guarantee that the method is atomic.

If you know how to do this, I also need to know whether or not, should the commit fail (due to a simultaneous write or something), the transaction is automatically re-attempted, or if I would have to manually catch a failure exception and re-call the method.

Thank you.

like image 842
So8res Avatar asked Sep 20 '09 12:09

So8res


1 Answers

Did you have a look at Django's transaction docs? Especially the @transaction.commit_on_success (source code) decorator. It commits the transaction if the decorated function returns without raising an exception. If an exception occurs, it does a rollback.

like image 162
Benjamin Wohlwend Avatar answered Sep 17 '22 15:09

Benjamin Wohlwend