Search code examples
djangoconcurrencydjango-database

How to change db objects thread safely in django?


For example, I have a model:

class Model1(models.Model):
   is_free = models.BooleanField(default=True)
   rel_object = models.ForeignKey(Model2, null=True, default=None)

There are some objects that are set as "free". I want to get the first one and set it to "not free" thread safe (I need guarantee that other thread can not change this object at the same moment):

model1 = Model1.objects.filter(is_free=True).first()
model1.is_free = False
model2.rel_object = model2
model2.save()

How to do that?


Solution

  • You might be interested in select_for_update. This enables you to lock the row until the transaction is committed.