41

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.

3 Answers 3

59

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)

4
  • So instead of doing a filter I can directly do select_for_update() on get? Jun 18, 2013 at 3:34
  • @IndradhanushGupta No, the order isn't correct. You use get on select_for_update() as get returns an object, not a QuerySet.
    – minmaxavg
    Jan 2, 2016 at 2:46
  • 1
    I didn't the get the 1.5 thingie in your last statement. pls clarify Sep 13, 2020 at 6:38
  • 1.5 refers to the version of Django. The default behavior is for the lock to be in place until the end of the request.
    – NFern
    Sep 16, 2021 at 22:06
44

You can also use select_for_update with get_object_or_404 function:

from django.db import transaction
from django.shortcuts import get_object_or_404

with transaction.atomic():
    obj = get_object_or_404(MyModel.objects.select_for_update(), pk=pk)
    # do some stuff with locked obj
0
0

Just after select_for_update().filter(), you can put .first() which returns the 1st object of a queryset to update it with save() as shown below. *You can see my question and answer explaining more about select_for_update() in Django:

                                                                # Here
ob = MyModel.objects.select_for_update().filter(some conditions).first()
ob.field_1 = 'some value'
ob.save()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.