SQLAlchemy: a better way for update with declarative?

Hadrien picture Hadrien · Apr 13, 2010 · Viewed 46.2k times · Source

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!

Answer

Ants Aasma picture Ants Aasma · Apr 13, 2010

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