推荐学习书目
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 · Aug 15, 2023 · 1734 views
    This topic created in 1026 days ago, the information mentioned may be changed or developed.
    • 程序 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
    • 线上遇到这种问题蛮难排查的,记一下
    Supplement 1  ·  Aug 15, 2023
    两个程序更新不同字段,程序很简单,上锁没必要,直接 save 了,结果悲剧了查了好久
    7 replies    2023-08-23 15:57:57 +08:00
    aapeli
        1
    aapeli  
       Aug 15, 2023
    # select_for_update

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

    ```
    wuwukai007
        3
    wuwukai007  
    OP
       Aug 15, 2023
    @aapeli 这里两个程序更新的不同字段,类似 update user set email='xx' where username='xx', 另一个 update user set age=30 where username='xx' ,这个没必要用锁,互相不影响的
    aapeli
        4
    aapeli  
       Aug 15, 2023
    提一点:楼主的 update_fields 可以解决不同字段同时更新的问题,但可能无法解决并发更新相同字段的问题
    fantathat
        5
    fantathat  
       Aug 15, 2023 via iPhone
    是的呀
    vishun
        6
    vishun  
       Aug 15, 2023
    用乐观锁
    45HXlKzal6W56zUJ
        7
    45HXlKzal6W56zUJ  
       Aug 23, 2023   ❤️ 1
    所以不要用 save ,用 update ,
    update 只更新某个字段,save 是全部更新为当前对象的信息
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   870 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 20:50 · PVG 04:50 · LAX 13:50 · JFK 16:50
    ♥ Do have faith in what you're doing.