For example, I have model:
class CacheMetaData(models.Model):
count = models.IntegerField(default=0)
def inc(self):
self.count += 1
self.save()
If I define method inc()
like above, then Django will execute a SQL statement like:
UPDATE the_table set count = 1 where id = 1
This way lead to race condition so that count
might not be correctly increased. I want Django to execute:
update the_table set count = count + 1
So that count will always be correctly increased.
Can Django do that? If yes, how to define the field count
?
according to django documentation you can use F expression like below:
from django.db.models import F
class CacheMetaData(models.Model):
count = models.IntegerField(default=0)
def inc(self):
self.count = F("count") + 1
self.save()
in your version django increases count
memory value by 1 and set it to database and can lead to race condition but in this version increasing process executes by database and the database value of count
increases by 1.
note: if you want to use count
value in your code, you need to run self.refresh_from_db()
to update memory from db.