If I do a select_for_update, when/how does that lock get released? Some example code:
for rec_id in list(1,2,3):
record = MyModel.objects.select_for_update().get(pk=rec_id)
# Do several things to this record
record.save()
Is the lock freed after the save()
or is it freed after the view returns and the entire transaction is complete? How can I control the granularity of the lock?
The docs don't seem to say: https://docs.djangoproject.com/en/1.6/ref/models/querysets/#select-for-update
The select_for_update method offered by the Django ORM solves the problem of concurrency by returning a queryset that locks all the rows that belong to this queryset until the outermost transaction it is inside gets committed thus preventing data corruption.
The SELECT command acquires a lock of this mode on referenced tables. In general, any query that only reads a table and does not modify it will acquire this lock mode.
The lock is active for the duration of the transaction, which is controlled by you. So you control the granularity of the lock by controlling the granularity of the transaction, using the usual methods: @transaction.atomic
, with transaction.atomic()
, ATOMIC_REQUESTS = True
, etc. See the transaction documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With