Al 20/08/12 18:53, En/na Sebastien Flory ha escrit:
Hi everyone,

I'm looking for the proper django way to do an update of an attribute on
my model instance, but only if the attribute current value is checked
agains't a condition, in an atomic way, something like this:

def use_money(self, value):
begin_transaction()
real_money = F('money')
if real_money >= value:
self.money = F('money') - value
self.save()
end_transaction()

I want to make sure that I avoid race condition so money never goes below 0.

Take a look at:

https://docs.djangoproject.com/en/1.4/topics/db/transactions/

Tying transactions to HTTP requests
===================================

The recommended way to handle transactions in Web requests is to tie them to the request and response phases via Django’s TransactionMiddleware.

It works like this: When a request starts, Django starts a transaction. If the response is produced without problems, Django commits any pending transactions. If the view function produces an exception, Django rolls back any pending transactions.

...

However, if you need more fine-grained control over how transactions are managed, you can use a set of functions in django.db.transaction to control transactions on a per-function or per-code-block basis.




HTH

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to