带有表达式的sqlalchemy更新列

带有表达式的sqlalchemy更新列,sqlalchemy,flask-sqlalchemy,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',

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

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语句在从控制台运行时起作用。错误是因为时间戳不能是

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

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

编辑:

您可以尝试使用
synchronize\u session
作为
“评估”

由于您只更新一行,因此可以执行以下操作:

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

您可以将此语法用于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()

问题是什么?问题是:为什么它不起作用,我添加了错误消息…我想这是因为它试图使用字符串
“(现在()在时区'utc')”
作为值。尝试使用
Text(“(现在()时区为“utc”)”
这会告诉我:“无法在Python中计算当前条件。”InvalidRequestError:无法在Python中计算当前条件。为synchronize_session参数指定'fetch'或False。wrapping with sqlalchemy.text会产生相同的错误使用func.now和func.timezone时会发生什么情况?func.now()会产生相同的错误(“无法在Python中计算当前条件”)。只是为了确保我使用的是func“from sqlalchemy import func”,感谢您的建议,更新row对象并保存它应该可以工作,但我更喜欢使用数据库的“now()”,因为它不需要同步db服务器和app服务器的时钟。换句话说:我想要所有来自数据库的时间戳。