这是我的声明性模型:
import datetime
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Test(Base):
__tablename__ = 'test'
id = Column(Integer, primary_key=True)
created_date = DateTime(default=datetime.datetime.utcnow)
然而,当我试图导入这个模块时,我得到这个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "orm/models2.py", line 37, in <module>
class Test(Base):
File "orm/models2.py", line 41, in Test
created_date = sqlalchemy.DateTime(default=datetime.datetime.utcnow)
TypeError: __init__() got an unexpected keyword argument 'default'
如果我使用Integer类型,我可以设置默认值。这是怎么呢
可以在sqlalchemy中使用TIMESTAMP。
from sqlalchemy import TIMESTAMP, Table, MetaData, Column, ...
... ellipsis ...
def function_name(self) -> Table:
return Table(
"table_name",
self._metadata,
...,
Column("date_time", TIMESTAMP),
)
... ellipsis ...
可以在sqlalchemy中使用TIMESTAMP。
from sqlalchemy import TIMESTAMP, Table, MetaData, Column, ...
... ellipsis ...
def function_name(self) -> Table:
return Table(
"table_name",
self._metadata,
...,
Column("date_time", TIMESTAMP),
)
... ellipsis ...
注意,要使server_default=func.now()和func.now()工作:
Local_modified = Column(DateTime, server_default=func.now(), onupdate=func.now())
你需要在DDL表中设置DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP。
例如
create table test
(
id int auto_increment
primary key,
source varchar(50) null,
Local_modified datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
collate=utf8mb4_bin;
否则,server_default= funcs .now(), onupdate= funcs .now()不会产生任何影响。