How to check if a Django model object is locked?

Is there a way to check if a Django model object is being fetched using select_for_update ()? Although the property "locked" in the following code does not actually exist, I want it to be.

with atomic():
   unlocked_obj = SomeModel.objects.get(pk=123)
   unlocked_obj.locked  # False

   locked_obj = SomeModel.objects.select_for_update().get(pk=123)
   locked_obj.locked  # True

      

+3


source to share


2 answers


The only way to test this is by enabling "select_for_update ( nowait = True )", if it is blocked Django will raise a DatabaseError.



https://docs.djangoproject.com/en/1.11/ref/models/querysets/#select-for-update

0


source


Open 2 django shells

shell1

with atomic():
    obj = SomeModel.objects.select_for_update().get(id=123)
    import time; time.sleep(10)

      



Shell2

with atomic():
    obj = SomeModel.objects.get(id=123)
    obj.save()

      

obj.save()

the command in Shell2 should be suspended until Shell1 exits the transaction.

-2


source







All Articles