What you're dealing with is called a "race condition". Transactions
ensure that a set of database operations occur together in a single
uninterrupted unit. That's not quite the exact definition, but if
you're picky, see this: http://en.wikipedia.org/wiki/Database_transaction

You can find documentation of Django's support for transactions here:
http://docs.djangoproject.com/en/dev/topics/db/transactions/

Note that this is dependent on your database supporting transactions.
If whatever reason your DB doesn't (e.g. using MySQL's MyISAM tables),
I think using Django's update call will work. Calling
MyModel.objects.filter(value=10, id=my_id).update(value=15) will
update the record with the given id to have a value of 15 if and only
if it's current value is already 10. It returns the number of records
it successfully modifies, so if there was no conflict, it'll return 1.
If it returns 0, you know that another process changed the value first
and that you'll need to get the new value to increment from the
database again.

-- Andrew

On Jun 6, 10:26 am, Masklinn <maskl...@masklinn.net> wrote:
> On 6 juin 09, at 15:34, AlexM <alex.marge...@gmail.com> wrote:
>
>
>
> > In one of my views i am using a custom manager , the custom manager
> > finds a user , alters his "balance" (where balance is an integer
> > value) , and then saves the user with the new balance.
>
> > The problem occurs when http requests coming really fast on that
> > view.
>
> > Lets say the "original" value of a users balance is 10 .
> > Two requests are made , each one asking for the users balance to be
> > credited plus 5 of the original one.
> > The "perfect" solution would be the first requests to be
> > processed ,saved and then the second to do the same.
>
> > However what happens is that the first request will come , it will do
> > its query and load the object , and the second request will also do
> > the query before the first request was able to complete the process of
> > saving the new balance, because of that the second request will have
> > and "out of date" balance which it will then save . So in the end the
> > user will have 10 (origina ballance) + 5 (second request) = 15 on his
> > balance when he should have 20.
>
> > What could i do to prevent this from happening ?
>
> Use transactions?
--~--~---------~--~----~------------~-------~--~----~
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