Skip to content
Advertisement

Atomic increment of a counter in django

I’m trying to atomically increment a simple counter in Django. My code looks like this:

JavaScript

If I understand Django correctly, this should wrap the function in a transaction and make the increment atomic. But it doesn’t work and there is a race condition in the counter update. How can this code be made thread-safe?

Advertisement

Answer

Use an F expression:

JavaScript

either in update():

JavaScript

or on the object instance:

JavaScript

Remember to specify update_fields, or you might encounter race conditions on other fields of the model.

A note on the race condition avoided by using F expressions has been added to the official documentation.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement