使用 django orm 生成更新查询

2022-01-17 00:00:00 python django sql-update orm

问题描述

我需要使用 django orm 来实现这个查询:

I need to implement this query using django orm:

update table set field=field+1 where id=id

我不想用这个:

o = model.objects.get(id=id)
o.field+=1
o.save()

因为它使用 select 和 when update,而不是线程安全的.

because it use select and when update, and not thread safe.

如何通过 orm 实现?

How to implement this via orm?


解决方案

前面的回答者都有部分解决方案:你应该使用 updateF():

Both the previous answerers have part of the solution: you should use update in conjunction with F():

Model.objects.filter(id=id).update(field=F('field') +1))

注意,这是一个就地更新,根本不需要 SELECT.

Note this does an in-place UPDATE without any need for SELECT at all.

相关文章