在sqlalchemy中设置server_default失败

时间:2015-07-24 13:16:50

标签: python postgresql sqlalchemy

这是我希望SQLAlchemy做的事情:

blesk_dev=# alter table address add column reg_at timestamp without time zone default (now() at time zone 'utc');
ALTER TABLE

也就是说,我想为列设置默认的UTC时间。在纯psql中,如上所示,这成功了。

这就是它在SQLAlchemy代码中的样子:

reg_at = db.Column(db.DateTime, server_default="(now() at time zone 'utc')")

但是当我尝试迁移时,我得到了这个:

sqlalchemy.exc.ProgrammingError: (ProgrammingError) syntax error at or near "utc"
LINE 1: ...STAMP WITHOUT TIME ZONE DEFAULT '(now() at time zone 'utc')'
                                                                 ^
 "ALTER TABLE address ADD COLUMN reg_at TIMESTAMP WITHOUT TIME ZONE DEFAULT '(now() at time zone 'utc')'" {}

因此,我认为单/双引号存在问题。

我试过

"(now() at time zone \'utc\')"

但是这给我带来了同样的错误。

然后我交换了引号:

'(now() at time zone "utc")'
'(now() at time zone \"utc\")'

无济于事:

sqlalchemy.exc.DataError: (DataError) invalid input syntax for type timestamp: "(now() at time zone "utc")"
 'ALTER TABLE address ADD COLUMN reg_at TIMESTAMP WITHOUT TIME ZONE DEFAULT \'(now() at time zone "utc")\''

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

考虑使用sqlalchemy的text函数:

from sqlalchemy import text
reg_at = db.Column(db.DateTime, server_default=text('(now() at time zone "utc")'))