推荐学习书目
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
miniyao
V2EX  ›  Python

Flask-SQLAlchemy 更新(update) 数据,还有必要 db.session.add(foo) 吗?

  •  
  •   miniyao · Aug 12, 2020 · 4950 views
    This topic created in 2124 days ago, the information mentioned may be changed or developed.

    有些案例中,update 数据对象时,会 加一行 db.session.add(foo),有些不加。不清楚哪种才是规范操作?

    def edit():
        user = User.query.get(5)
        user.name = 'New Name'
        db.session.add(user)
        db.session.commit()
    
    def edit():
        user = User.query.get(5)
        user.name = 'New Name'
        db.session.commit()
    
    7 replies    2020-08-12 16:57:08 +08:00
    hushao
        1
    hushao  
       Aug 12, 2020
    加不加都可以,add 操作已有记录会更新
    knightdf
        2
    knightdf  
       Aug 12, 2020
    update 不用加,直接 db.session.commit()
    6d6f33
        3
    6d6f33  
       Aug 12, 2020   ❤️ 1
    当然是显式声明是最好的。就是加 add 。
    kayseen
        4
    kayseen  
       Aug 12, 2020
    一条更新我也是加的, 如果是更新多条数据, 分别 add, 然后一次 commit
    CRVV
        5
    CRVV  
       Aug 12, 2020
    https://docs.sqlalchemy.org/en/13/orm/tutorial.html#adding-and-updating-objects

    文档里写得很清楚,不用 add
    add 的作用是 adding object,updating object 不用 add
    miniyao
        6
    miniyao  
    OP
       Aug 12, 2020
    @CRVV 狗书的作者,光头大叔的 flask 教程里是有加的:

    github.com/miguelgrinberg/flasky/blob/master/app/main/views.py

    功能上没区别,作用可能就是 #3 楼说的语义上明显吧。
    loading
        7
    loading  
       Aug 12, 2020 via Android
    无脑最后 commit
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2652 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 10:22 · PVG 18:22 · LAX 03:22 · JFK 06:22
    ♥ Do have faith in what you're doing.