The documentation for Django 2.2, which I’m using, gives the following example usage for
from django.db import transaction entries = Entry.objects.select_for_update().filter(author=request.user) with transaction.atomic(): for entry in entries: ...
Using this approach, one would presumably mutate the model instances assigned to
entry and call
save on these.
There are cases where I’d prefer the alternative approach below, but I’m unsure whether it would work (or even make sense) with
with transaction.atomic(): Entry.objects.select_for_update().filter(author=request.user).update(foo="bar", wobble="wibble")
The documentation states that the lock is created when the queryset is evaluated , so I doubt the
update method would work. As far as I’m aware
update just performs an
UPDATE ... WHERE query, with no
SELECT before it. However, I would appreciate it if someone more experienced with this aspect of the Django ORM could confirm this.
A secondary question is whether a lock even adds any protection against race conditions if one makes a single
UPDATE query against the locked rows. (I’ve entered this train of thought because I’m refactoring code that uses a lock when updating the values of two columns of a single row.)