在Django的2.2文件,我使用的,给出了下面的例子中使用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:
...
Run Code Online (Sandbox Code Playgroud)
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")
Run Code Online (Sandbox Code Playgroud)
The documentation states that the lock is created when the queryset is evaluated, so …