这是我的声明性模型:

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 ...  

其他回答

DateTime没有默认键作为输入。默认键应该是Column函数的输入。试试这个:

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 = Column(DateTime, default=datetime.datetime.utcnow)

您也可以为默认的DateTime使用sqlalchemy内置函数

from sqlalchemy.sql import func

DT = Column(DateTime(timezone=True), default=func.now())

可以在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 ...  

使用默认参数datetime.now:

from sqlalchemy import Column, Integer, DateTime
from datetime import datetime
class Test(Base):
     __tablename__ = 'test'
     id = Column(Integer, primary_key=True)
     created_at = Column(DateTime, default=datetime.now)
     updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)                                                            

注意,要使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()不会产生任何影响。