#34827 closed Bug (invalid)

select_for_update example raises TransactionManagementError

Reported by: Jim Nicholls Owned by: nobody
Component: Documentation Version: 4.2
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description (last modified by Jim Nicholls)

The example for select_for_update at https://docs.djangoproject.com/en/4.2/ref/models/querysets/#select-for-update shows select_for_update being used before starting the transaction. With Django 4.2.5, this raises a TransactionManagementError.

Traceback (most recent call last):
  File "/site-packages/django/db/models/query.py", line 633, in get
    num = len(clone)
  File "/site-packages/django/db/models/query.py", line 380, in __len__
    self._fetch_all()
  File "/site-packages/django/db/models/query.py", line 1881, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/site-packages/django/db/models/query.py", line 91, in __iter__
    results = compiler.execute_sql(
  File "/site-packages/django/db/models/sql/compiler.py", line 1549, in execute_sql
    sql, params = self.as_sql()
  File "/site-packages/django/db/models/sql/compiler.py", line 816, in as_sql
    raise TransactionManagementError(
django.db.transaction.TransactionManagementError: select_for_update cannot be used outside of a transaction.

I think the example should be:

from django.db import transaction

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

Change History (2)

comment:1 by Jim Nicholls, 14 months ago

Description: modified (diff)

comment:2 by Simon Charette, 14 months ago

Resolution: invalid
Status: newclosed

Querysets are lazily evaluated, and thus only the evaluating part needs to be run within a transaction

When the queryset is evaluated (for entry in entries in this case), all matched entries will be locked until the end of the transaction block

Note: See TracTickets for help on using tickets.
Back to Top