How to use select_for_update to 'get' a Query in Django?

Indradhanush Gupta picture Indradhanush Gupta · Jun 18, 2013 · Viewed 23.8k times · Source

As the Django Documentation says, select_for_update returns a Queryset. But get does not. Now I have a query which I am sure is going to return only one tuple. But I also need to acquire locks for this transaction. So I am doing something like:

ob = MyModel.objects.select_for_update().filter(some conditions)

Now I need to modify some values of ob. But ob is a Queryset. This seems pretty simple, but beats me. I'm pretty new to Django. Some advice please.

Answer

Yuji 'Tomita' Tomita picture Yuji 'Tomita' Tomita · Jun 18, 2013

Just call get, slice it, etc. and save as usual. The lock is in place through the transaction.

ob = MyModel.objects.select_for_update().get(pk=1)

Any changes are committed at the end of the transaction (which by default through 1.5 is per-request)