I’m going into my fourth month working at Mobify. I’m learning tons of stuff on the job, so one great way to solidify it in my memory will be to blog about what I’m picking up along the way. Maybe someone else will also find it useful.
One neat thing I learned today is that you can update django models base on existing fields at the time the .save() method gets called. This can be extremely useful when trying to avoid race conditions.
account = Account.objects.get(account_number='111111111') account.balance += 1000 account.save()
In this case, the new account balance gets incremented by 1000, but another thread could update the balance and modify the account balance after you get the model and before you have a chance to save. The value of balance you are incrementing is going to be stale. You will end up incrementing the old value of balance and saving the incorrect value.
The following code is much safer. It will do the same thing, but it will only query the value of balance when the .save() method is called.
from django.db.models import F account = Account.objects.get(account_number='111111111') account.balance = F('balance') + 1000 account.save()