sqlalchemy用表达式更新列

时间:2015-03-31 21:22:13

标签: sqlalchemy flask-sqlalchemy

我想更新一行设置列上表达式的结果,例如:

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

此代码给出了以下错误:

(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')", 

这应该在sql中转换为:

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

从控制台运行时,此SQL语句可以正常工作

2 个答案:

答案 0 :(得分:0)

错误是因为时间戳不能是"(now() at time zone 'utc')"

的字符串

您可以尝试使用Text()函数或func.now()或以UTC格式获取时间

db.func.timezone('utc', db.func.now())

修改

您可以尝试将synchronize_session用作'evaluate'

由于您只更新了一行,因此您可以这样做:

mytable_row_obj = MyTable.query.filter_by(id=the_id).one()
mytable_row_obj.my_col = ... What ever you want to put here ...
session.commit()

答案 1 :(得分:0)

您可以将此语法与sqlalchemy func对象一起使用,如下面的代码:

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