SQLAlchemy:使用声明式更新的更好方法? [英] SQLAlchemy: a better way for update with declarative?

查看:92
本文介绍了SQLAlchemy:使用声明式更新的更好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是SQLAlchemy新手.

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))

当我知道没有将对象加载到会话中的用户ID时,我会像这样更新该用户:

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)

我不喜欢使用User.__table__,我应该不再为此担心吗?

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

有更好的方法吗?

谢谢!

推荐答案

ORM级别还具有一些更新功能.它还不能处理任何棘手的情况,但是对于单行更新(或批量更新)的微不足道的情况,它可以正常工作.它甚至遍历所有已加载的对象,并对它们也应用更新.您可以像这样使用它:

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"})

这篇关于SQLAlchemy:使用声明式更新的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆