Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 226
Indradhanush Gupta Avatar asked Jun 18 '13 01:06

Indradhanush Gupta


People also ask

How do I search for a query in Django?

You would use the __search operator. It's documented in the Django QuerySet API Reference. There's also istartswith, which does a case-insensitive starts-with search. Note that __search is only available in MySQL and requires direct manipulation of the database to add the full-text index.

What is Select_for_update 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 rows?

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. Conflicts with the EXCLUSIVE and ACCESS EXCLUSIVE lock modes.


1 Answers

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)

like image 59
Yuji 'Tomita' Tomita Avatar answered Oct 23 '22 20:10

Yuji 'Tomita' Tomita