Today I Learned….

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()
Category(s): Uncategorized

Leave a Reply

Your email address will not be published. Required fields are marked *

 

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>