Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: a better way for update with declarative?

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!

like image 890
Hadrien Avatar asked Apr 13 '10 18:04

Hadrien


People also ask

How do I update data in SQLAlchemy?

Update table elements in SQLAlchemy. Get the books to table from the Metadata object initialized while connecting to the database. Pass the update query to the execute() function and get all the results using fetchall() function. Use a for loop to iterate through the results.

Is SQLAlchemy efficient?

SQLAlchemy is very, very fast. It's just that users tend to be unaware of just how much functionality is being delivered, and confuse an ORM result set with that of a raw database cursor. They are quite different, and SQLAlchemy offers many options for controlling the mixture of "raw" vs.

What is Declarative in SQLAlchemy?

The Declarative system is the typically used system provided by the SQLAlchemy ORM in order to define classes mapped to relational database tables. However, as noted in Classical Mappings, Declarative is in fact a series of extensions that ride on top of the SQLAlchemy mapper() construct.


1 Answers

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"}) 
like image 114
Ants Aasma Avatar answered Oct 10 '22 06:10

Ants Aasma