使用django orm生成更新查询 [英] generate update query using django orm

查看:122
本文介绍了使用django 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和更新,而不是线程安全。

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

推荐答案

以前的答复者都有部分解决方案:您应该使用更新 F()

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))

注意这是一个就地UPDATE,而不需要SELECT。

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

这篇关于使用django orm生成更新查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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