Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy update column with an expression

I want to update a row setting the result of an expression on a column, ex:

MyTable.query.filter_by(id=the_id).update({
  "my_col": "(now() at time zone 'utc')"
})

This code give me the following error :

(DataError) invalid input syntax for type timestamp: "(now() at time zone 'utc')"
LINE 1: ...12bf98a-1ee9-4958-975d-ee99f87f1d4a', my_col='(now() at...
                                                             ^
 'UPDATE my_table SET my_col=%(redeemed_at)s WHERE id = %(id_1)s' {'my_col': "(now() at time zone 'utc')", 

this should translate in sql to :

update my_table set my_col = (now() at time zone 'utc') where id = ?;

this SQL statement works when run from the console

like image 916
Max L. Avatar asked Aug 07 '26 13:08

Max L.


1 Answers

You can use this syntax with sqlalchemy func object, as the following code:

from sqlalchemy.sql.expression import func

#  get a sqlalchemy session
session.query(YourTable).filter_by(id=the_id).update(values={'my_col': func.utc_timestamp()}, synchronize_session=False)

session.commit()
like image 174
SenBin Yu Avatar answered Aug 09 '26 10:08

SenBin Yu