没注意 django model.save 有 update_fields 参数更新指定字段,出 bug 后好难排查

268 天前
 wuwukai007

user = User.object.filter(username='xxx', age=30).update(age=20)
user = User.object.get(username='xxx')
# 此时 age=30
user.email = 'xxx@gmail.com'
user.save()

1027 次点击
所在节点    Python
7 条回复
aapeli
268 天前
# select_for_update

```
user = User.objects.select_for_update().get(username='xxx')
# 此时 age=30
user.email = 'xxx@gmail.com'
user.save()

```
aapeli
268 天前
wuwukai007
268 天前
@aapeli 这里两个程序更新的不同字段,类似 update user set email='xx' where username='xx', 另一个 update user set age=30 where username='xx' ,这个没必要用锁,互相不影响的
aapeli
268 天前
提一点:楼主的 update_fields 可以解决不同字段同时更新的问题,但可能无法解决并发更新相同字段的问题
fantathat
268 天前
是的呀
vishun
268 天前
用乐观锁
dicc
260 天前
所以不要用 save ,用 update ,
update 只更新某个字段,save 是全部更新为当前对象的信息

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/965395

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX