The documentation for Django 2.2, which I'm using, gives the following example usage for select_for_update:
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 select_for_update.
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.)
bulk_updatewould probably be more efficient as it would only use one UPDATE query rather than one per row.qs.get(foo="bar")would cause a Queryset based onqsto be evaluated, meaning that at least I wouldn't have to iterate through a QuerySet containing a single result.