django - 使用计数自动更新查询集中的每个实例

标签 django django-queryset

我正在尝试以原子方式更新查询集的字段。我有这样的东西:

counter = 0
for row in myQuerySet:
  row.myField = counter
  counter = counter + 1
  row.save()

这可行,但我想以原子方式执行此操作,因为我有数百个寄存器,这是浪费时间。我需要这样的东西:

counter = 0
myQuerySet.update(myField=(counter+=1))

但这不起作用。正确的语法是什么?

最佳答案

That works, but I want to do this atomically […]

通常,答案是使用 QuerySet.update method 。当您想要对查询集中的所有实例执行相同的操作(或不需要动态更改的操作)时,这会起作用。

由于您要执行的操作似乎需要依次对每个实例进行动态更改,因此您可以改用 select_for_update method .

from django.db import transaction

dolors = LoremIpsum.objects.select_for_update().filter(dolor=True)

with transaction.atomic():
    counter = 0
    for lorem_ipsum in dolors:
        lorem_ipsum.amet = counter
        counter += 1
        lorem_ipsum.save()

documentation for select_for_update说这可以满足您的要求:

All matched entries will be locked until the end of the transaction block, meaning that other transactions will be prevented from changing or acquiring locks on them.

由于查询集导致项目“锁定直到事务 block 结束”,因此您需要使用上面的 transaction.atomic 在事务 block 内执行操作。

关于django - 使用计数自动更新查询集中的每个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40909357/

相关文章:

python - Django 装饰器根据用户类型进行重定向

python - 是否有任何好的选项可以将 Django 站点烘焙为静态文件?

python - Django-cms 显示菜单 : How to show menu under current page?

django - 在具有ManyToMany字段的QuerySet上输出values()

python - 如何在查询集中包含外键的详细信息字段(django 和rest_api)

python - Django 日期时间字段 - 在 View 中转换为时区

Django 编辑配置文件 - 'bool' 对象不可调用

python - Django Count和Sum批注相互干扰

python - Django:通过多个 ID 过滤查询集

python - 在 Django rest api 中查询最小和最大大小