Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What clears the lock created by select_for_update in Django?

Tags:

django

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

like image 776
boatcoder Avatar asked Feb 22 '14 18:02

boatcoder


People also ask

What is Select_for_update in Django?

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.

Which method in Django ORM acquires a lock on the specific row?

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.


1 Answers

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.

like image 82
Kevin Christopher Henry Avatar answered Sep 18 '22 05:09

Kevin Christopher Henry