V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
wuwukai007
V2EX  ›  Python

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

  •  
  •   wuwukai007 · 256 天前 · 1014 次点击
    这是一个创建于 256 天前的主题,其中的信息可能已经有所发展或是发生改变。
    • 程序 A1, 数据 A ,将 age 由 30 更新为 20
    
    user = User.object.filter(username='xxx', age=30).update(age=20)
    
    • 程序 A2 在程序 A1 数据库提交之前拿到了 A 对象, 并只更新 email 字段
    user = User.object.get(username='xxx')
    # 此时 age=30
    user.email = '[email protected]'
    user.save()
    
    
    • user.save() 默认更新全部字段,又会把 age 变回 30
    • 线上遇到这种问题蛮难排查的,记一下
    第 1 条附言  ·  256 天前
    两个程序更新不同字段,程序很简单,上锁没必要,直接 save 了,结果悲剧了查了好久
    7 条回复    2023-08-23 15:57:57 +08:00
    aapeli
        1
    aapeli  
       256 天前
    # select_for_update

    ```
    user = User.objects.select_for_update().get(username='xxx')
    # 此时 age=30
    user.email = '[email protected]'
    user.save()

    ```
    wuwukai007
        3
    wuwukai007  
    OP
       256 天前
    @aapeli 这里两个程序更新的不同字段,类似 update user set email='xx' where username='xx', 另一个 update user set age=30 where username='xx' ,这个没必要用锁,互相不影响的
    aapeli
        4
    aapeli  
       256 天前
    提一点:楼主的 update_fields 可以解决不同字段同时更新的问题,但可能无法解决并发更新相同字段的问题
    fantathat
        5
    fantathat  
       256 天前 via iPhone
    是的呀
    vishun
        6
    vishun  
       256 天前
    用乐观锁
    dicc
        7
    dicc  
       248 天前   ❤️ 1
    所以不要用 save ,用 update ,
    update 只更新某个字段,save 是全部更新为当前对象的信息
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2989 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 13:58 · PVG 21:58 · LAX 06:58 · JFK 09:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.