以原子方式更新queryset中的每个实例 [英] Update every instance in a queryset with a count atomically

查看:92
本文介绍了以原子方式更新queryset中的每个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to update a field of a queryset atomically. I have something like this:

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

但是我想这样做是因为我有数百个寄存器,而且浪费时间。我需要这样的东西:

That works, but I want to do this atomically, because I have hundreds of registers and it is a waste of time. I need something like this:

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

但这不行。这是正确的sintax?

But that does not work. What is the correct sintax for this?

推荐答案


这是有效的,但我想这样做[...]

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

通常,答案是使用 QuerySet.update 方法。当您想要做同样的事情(或不需要动态更改的内容)到查询器中的所有实例时都可以。

Often, the answer is to use the QuerySet.update method. That works when you want to do the same thing – or something that doesn't need to change dynamically – to all the instances in a queryset.

由于您想要的操作执行似乎需要依次对每个实例进行动态更改,您可以使用 select_for_update 方法

Since the operation you want to perform appears to need a dynamic change to each instance in turn, you can instead use the 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()

文档为 select_ for_update 说这是你想要的:

The documentation for select_for_update says this does what you want:


所有匹配的条目将被锁定,直到结束的交易块,这意味着其他交易将被阻止更改或获取锁定。

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.

因为查询导致项目要锁定到事务块结束,您需要使用 transaction.atomic 如上所述在事务块内执行操作。

Because the queryset causes the items to be "locked until the end of the transaction block", you need to perform your operations inside a transaction block using transaction.atomic as above.

这篇关于以原子方式更新queryset中的每个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆