Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple update in sqlalchemy

UserTable is:

  • id (INT)

  • name (STR)

  • last_login (DATETIME)

Serving a web page request i have a user id in hand and I only wish to update the last_login field to 'now'.

It seems to me that there are 2 ways:

  1. issue a direct SQL using db_engine (losing the mapper)

  2. OR query the user first and then update the object

Both work fine but look quite disgusting in code.

Is anyone aware of a more elegant way of doing an update-with-no-query using sqlalchemy? Is there another ORM who has got this right?

Thanks

like image 884
gnosis Avatar asked Jun 19 '09 10:06

gnosis


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.


1 Answers

Assuming you have a mapper UserTable in place:

DBSession.query(UserTable).filter_by(id = user_id).\
    update({"last_login":datetime.datetime.now()}, synchronize_session=False)

Additional parameters in the docs.

like image 64
ebo Avatar answered Oct 10 '22 19:10

ebo