select_for_update Documentation is confusing(?)

58 views
Skip to first unread message

Philoj Johny

unread,
Feb 15, 2019, 7:40:51 AM2/15/19
to django...@googlegroups.com
In the documentation for select_for_update, given code example is:
from django.db import transaction

entries = Entry.objects.select_for_update().filter(author=request.user)
with transaction.atomic():
    for entry in entries:
        ...

At the same time, below in the description it says that:

Evaluating a queryset with select_for_update() in autocommit mode on backends which support SELECT ... FOR UPDATE is a TransactionManagementError error because the rows are not locked in that case.

Does this mean that the above code example will raise TransactionManagementError , since the select_for_update_query is evaluated outside atomic block?
(I have'nt actually tried this out yet, will soon. I think may be a correction is required in the code example)

Simon Charette

unread,
Feb 15, 2019, 2:18:27 PM2/15/19
to Django users
Hello Philoj,

> Does this mean that the above code example will raise TransactionManagementError...

It won't cause a TransactionManagementError because of the lazy nature of queryset.

Even if the QuerySet.select_for_update() call is made outside of the atomic block the query
is really only executed when entries are iterated over.

Given the documentation clearly mentions "Evaluating a queryset" and "Building a queryset"
I don't think it's worth amending it.

Cheers,
Simon

Simon Charette

unread,
Feb 15, 2019, 2:19:19 PM2/15/19
to Django users
I meant, and not "Building a queryset" in my previous reply.

Philoj Johny

unread,
Mar 2, 2019, 7:49:25 AM3/2/19
to Django users
I apologize for such a late reply. I am new to mail groups and all.

Thank you very much for pointing this out. Guess it's easy to forget querysets are lazy ;)
Reply all
Reply to author
Forward
0 new messages