Search code examples
djangodatetimeatomic

Django: atomic DateTimeField read and write


I have a Django model User with field balance, and maintain a balance_last_updated DateTimeField with it.

In order to update balances race-condition free, I need to atomically read and then set balance_last_updated in my Django view. That way, any threads updating the balance will do so for distinct time periods (correct?).

How do I do this? Note that I am using MySQL MyISAM tables, which seem to not support Django transactions.


Solution

  • If you're on Django 1.4, you can use select_for_update to achieve this. But only if your database backend supports transactions. MyISAM doesn't, so I suggest switching to the InnoDB engine or PostgreSQL if atomicity (or ACID in general) is of any importance for your project.