我有**Person
型号**,如下所示:
# "store/models.py"
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=30)
然后,当使用select_for_update()和update()of一个查询集时,如下所示。* 我使用Django 3.2.16:
# "store/views.py"
from django.db import transaction
from .models import Person
from django.http import HttpResponse
@transaction.atomic
def test(request):
# Here # Here
print(Person.objects.select_for_update().update(name="Tom"))
# Here # Here
print(Person.objects.select_for_update().all().update(name="Tom"))
# Here # Here
print(Person.objects.select_for_update().filter(id=1).update(name="Tom"))
return HttpResponse("Test")
只有**UPDATE
查询在没有SELECT FOR UPDATE
查询的情况下运行,如下所示。* 我使用PostgreSQL**,下面的这些日志是PostgreSQL的查询,您可以选中在PostgreSQL上,如何记录带有事务查询(如“开始”和“COMMIT”)的查询:
而当使用select_for_update()
和对象的**保存()**时,如下所示:
# "store/views.py"
from django.db import transaction
from .models import Person
from django.http import HttpResponse
@transaction.atomic
def test(request):
# Here
person1 = Person.objects.select_for_update().first()
person1.name = "Tom"
person1.save() # Here
# Here
person2 = Person.objects.select_for_update().all().first()
person2.name = "Tom"
person2.save() # Here
# Here
person3 = Person.objects.select_for_update().filter(id=1).first()
person3.name = "Tom"
person3.save() # Here
# Here
person4 = Person.objects.select_for_update().get(id=1)
person4.name = "Tom"
person4.save() # Here
return HttpResponse("Test")
运行**SELECT FOR UPDATE
查询和UPDATE
查询**,如下所示:
并且,当使用select_for_update()
和查询集的**count()**时,如下所示:
# "store/views.py"
from django.db import transaction
from .models import Person
from django.http import HttpResponse
@transaction.atomic
def test(request):
# Here # Here
print(Person.objects.select_for_update().count())
# Here # Here
print(Person.objects.select_for_update().all().count())
# Here # Here
print(Person.objects.select_for_update().filter(id=1).count())
return HttpResponse("Test")
运行**SELECT
查询**,而不是**SELECT FOR UPDATE
查询**,如下所示:
当使用select_for_update()
和**len()**时,这是Python中的内置函数,如下所示:
# "store/views.py"
from django.db import transaction
from .models import Person
from django.http import HttpResponse
@transaction.atomic
def test(request):
# Here # Here
print(len(Person.objects.select_for_update()))
# Here # Here
print(len(Person.objects.select_for_update().all()))
# Here # Here
print(len(Person.objects.select_for_update().filter(id=1)))
return HttpResponse("Test")
运行**SELECT FOR UPDATE
查询**,而不是**SELECT
查询**,如下所示:
那么,除了我上面展示的,还有其他select_for_update()
在Django中不起作用的情况吗?
1条答案
按热度按时间s4n0splo1#
是的,在Django中还有其他
select_for_update()
不起作用的情况。将
select_for_update()
与查询集的delete()**一起使用时,如下所示:仅运行**
DELETE
查询**,而不运行**SELECT FOR UPDATE
查询**,如下所示。而将
select_for_update()
与对象的delete()
一起使用时,如下所示:SELECT FOR UPDATE
查询和**DELETE
查询**的运行方式如下所示: