views:

501

answers:

1

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.

+5  A: 

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.

piquadrat
Yes this is the appropriate thing to use. I think the OP was concerned because the documentation only refers to these in conjunction with views, not model methods, but looking at the source there's nothing in there that wouldn't work outside a view.
Daniel Roseman
There's actually a note on that page of the documentation that says "Although the examples below use view functions as examples, these decorators can be applied to non-view functions as well."
piquadrat
Thanks. Do you happen to have any idea what happens if simultaneous writes are attempted? Does the transaction re-attempt, and if not, what does it throw?Thanks!
Nate
@Nate that depends on your database backend, it has nothing to do with Django. I don't know of any database backends that "re-attempt" failed transactions, but I'm not a DB guru.
Carl Meyer