我有以下SqlAlchemy模型:
class SchemaVersion(Base):
__tablename__ = 'schema_version'
timestamp = Column(DateTime, default=datetime.datetime.utcnow, primary_key=True)
version = Column(String)
notes = Column(String)
我能找到的最接近的是:
statement = insert(SchemaVersion).values(version='v1.0.0',
notes='Initial schema')
print(statement.compile(engine, compile_kwargs={'literal_binds': True}))
engine
是我正在使用的引擎(Postgres)
生成的打印SQL为:
INSERT INTO schema_version (timestamp, version, notes) VALUES (%(timestamp)s, 'v1.0.0', 'Initial schema')
问题当然是%(timestamp)s
如何传递now()
作为值或让SqlAlchemy为我使用默认值?如果我尝试:
statement = insert(SchemaVersion).values(timestamp=datetime.datetime.utcnow(),
version='v1.0.0',
notes='Initial schema')
我得到了错误:
NotImplementedError: Don't know how to literal-quote value datetime.datetime(2018, 8, 21, 9, 50, 11, 732957)
答案 0 :(得分:2)
尽管尚不清楚您为什么对产生带有绑定文字的SQL字符串感兴趣,但是在这种情况下,可以通过使用例如{{1}在数据库中产生时间戳来避免only simple types such as int
and str
are supported的事实}:
CURRENT_TIMESTAMP
这将编译成类似
的东西statement = insert(SchemaVersion).values(timestamp=func.current_timestamp(),
version='v1.0.0',
notes='Initial schema')