I have this accounts model in my django project, which stores the account balance(available money) of all users. Almost every deduction from the account of users is preceded by an amount check i.e. check if the user has x amount of money or more. If yes then go ahead and deduct the amount.
account = AccountDetails.objects.get(user=userid) if int(account.amount) >= fare: account.amount = account.amount-fare account.save() Now I want to put a lock in the first .get() statement, so that race conditions can be avoided. A user makes a request twice, and the application executes the above code twice simultaneously, causing one of the requests to override the other.
I found out that select_for_update() does exactly what I want. It locks the row until the end of the transaction.
account = AccountDetails.objects.select_for_update().get(user=userid) But it's only available in Django 1.4 or higher and I'm still using Django 1.3 and moving to a new version can't be done right now. Any ideas how can I achieve this in my present Django version?