SQLAlchemy: a better way for update with declarative?

丶灬走出姿态 提交于 2019-12-18 10:12:28

问题


I am a SQLAlchemy noob.

Let's say I have an user table in declarative mode:

class User(Base):
    __tablename__ = 'user'
    id = Column(u'id', Integer(), primary_key=True)
    name = Column(u'name', String(50))

When I know user's id without object loaded into session, I update such user like this:

ex = update(User.__table__).where(User.id==123).values(name=u"Bob Marley")
Session.execute(ex)

I dislike using User.__table__, should I stop worrying with that?

Is there a better way to do this?

Thanks!


回答1:


There's also some update capability at the ORM level. It doesn't handle any tricky cases yet but for the trivial case of single row update (or bulk update) it works fine. It even goes over any already loaded objects and applies the update on them also. You can use it like this:

session.query(User).filter_by(id=123).update({"name": u"Bob Marley"})



回答2:


You're working on clause level here, not on model/entity/object level. Clause level is lower than mapped objects. And yes, something have to be done to convert one terms into others.

You could also stay on object level and do:

session = Session()
u = session.query(User).get(123)
u.name = u"Bob Marley"
session.commit()

but it will be significantly slower since it leads to the mapped object construction. And I'm not sure that it is more readable.

In the example your provided I see the most natural and “right” solution. I would not worry about little __table__ magic.




回答3:


Similar functionality is available via the update() method on Table object.

class User(Base):
    __tablename__   = 'user'
    id = Column('id', Integer(), primary_key=True)
    name = Column('name', String(50))

stmt = User.__table__.update().where(User.id==5).values(name='user #5')

To use User.__table__ is how its done in SQLAlchemy.



来源:https://stackoverflow.com/questions/2631935/sqlalchemy-a-better-way-for-update-with-declarative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!