How can I update a model field based on its current value and avoid a race condition? The update task can be written as:
if (self.x == y):
self.x = z
self.save()
else:
raise Exception()
However, there is a race condition. I came up with the following solution:
from django.db import transaction
with transaction.atomic():
if (self.x == y):
self.x = z
self.save()
else:
raise Exception()
But is this safe and is there a better way?