django 过滤和更新
django filter and update
更新:
我为 select_for_update
做了一些测试。我正在使用 Django 1.8.12。我运行以下功能在不同的shell,连接到我本地的mariadb(引擎是InnoDB)。似乎 select_for_update
也锁定了其他行?不确定我是否以正确的方式进行了测试:
def with_sleep(resource):
try:
with transaction.atomic():
resource = resourceA.objects.select_for_update().filter(A=resource).first()
print('before sleep')
time.sleep(10)
print('after sleep')
resource.available = False
resource.save()
return True
except:
handle_exception()
def withouth_sleep(resource):
try:
with transaction.atomic():
print('try')
resource = resourceA.objects.select_for_update().filter(A=resource).first()
print('get resource')
resource.available = False
print('save')
resource.save()
return True
except:
handle_exception()
我先调用with_sleep(resource1)
函数,然后再调用without_sleep(resource2)
。 resource1
和 resource2
是我模型中的不同资源。从 shell 开始,我看到第二个函数在 try
之后被阻塞,直到第一个函数从睡眠中醒来。 resource2 的平均行是否也被锁定?
这个问题听起来可能很愚蠢。感谢您对测试的任何建议或任何更改。
原题:
我有一个资源模型,它检查资源是否可用,并且它 运行 在 2 个服务器中有多个 celery worker 每次都检索下一个可用资源。如果可用,将其状态更改为不可用并分配给任务。
例如:
Class resourceA(model.Model):
A = models.CharField(max_length=10)
available = models.BooleanField(default=True)
每次,我只想选择下一个可用资源并分配给任务。
如果我这样做
resource = resourceA.objects.filter(available=True).first()
if resource:
resource.available=False
resource.save()
然后其他工作人员可能会选择相同的资源并尝试更新它。
Django select_for_update
可以锁定条目。但是,我不想锁定和更新所有可用资源。
请问有什么方法可以一次性检索和更新吗?
select_for_update
将仅锁定行,因此在您的查询中使用 first()
将仅锁定一行。
因此 — 使用 select_for_update
.
更新:
我为 select_for_update
做了一些测试。我正在使用 Django 1.8.12。我运行以下功能在不同的shell,连接到我本地的mariadb(引擎是InnoDB)。似乎 select_for_update
也锁定了其他行?不确定我是否以正确的方式进行了测试:
def with_sleep(resource):
try:
with transaction.atomic():
resource = resourceA.objects.select_for_update().filter(A=resource).first()
print('before sleep')
time.sleep(10)
print('after sleep')
resource.available = False
resource.save()
return True
except:
handle_exception()
def withouth_sleep(resource):
try:
with transaction.atomic():
print('try')
resource = resourceA.objects.select_for_update().filter(A=resource).first()
print('get resource')
resource.available = False
print('save')
resource.save()
return True
except:
handle_exception()
我先调用with_sleep(resource1)
函数,然后再调用without_sleep(resource2)
。 resource1
和 resource2
是我模型中的不同资源。从 shell 开始,我看到第二个函数在 try
之后被阻塞,直到第一个函数从睡眠中醒来。 resource2 的平均行是否也被锁定?
这个问题听起来可能很愚蠢。感谢您对测试的任何建议或任何更改。
原题: 我有一个资源模型,它检查资源是否可用,并且它 运行 在 2 个服务器中有多个 celery worker 每次都检索下一个可用资源。如果可用,将其状态更改为不可用并分配给任务。
例如:
Class resourceA(model.Model):
A = models.CharField(max_length=10)
available = models.BooleanField(default=True)
每次,我只想选择下一个可用资源并分配给任务。 如果我这样做
resource = resourceA.objects.filter(available=True).first()
if resource:
resource.available=False
resource.save()
然后其他工作人员可能会选择相同的资源并尝试更新它。
Django select_for_update
可以锁定条目。但是,我不想锁定和更新所有可用资源。
请问有什么方法可以一次性检索和更新吗?
select_for_update
将仅锁定行,因此在您的查询中使用 first()
将仅锁定一行。
因此 — 使用 select_for_update
.