这是我的声明性模型:

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类型,我可以设置默认值。这是怎么呢


当前回答

您可能需要使用onupdate=datetime。现在,以便UPDATEs也改变last_updated字段。

对于python执行的函数,SQLAlchemy有两个默认值。

默认设置INSERT的值,只设置一次 onupdate也将值设置为UPDATE上的可调用结果。

其他回答

根据PostgreSQL文档:

现在,CURRENT_TIMESTAMP, LOCALTIMESTAMP返回事务的时间

这被认为是一个特性:目的是允许单个 事务要对“当前”时间有一致的概念,这样才能做到 同一事务中的多个修改具有相同的时间戳。

如果不想使用事务时间戳,可能需要使用statement_timestamp或clock_timestamp。

statement_timestamp ()

返回当前语句的开始时间(更具体地说, 从客户端接收最新命令消息的时间)。 statement_timestamp

clock_timestamp ()

返回实际的当前时间,因此它的值甚至会改变 在一个SQL命令中。

对于mariadb,这对我来说是有效的:

from sqlalchemy import Column, Integer, String, DateTime, TIMESTAMP, text
from sqlalchemy.sql import func
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Test(Base):
  __tablename__ = "test"

  id              = Column(Integer, primary_key=True, autoincrement=True)
  name            = Column(String(255), nullable=False)
  email           = Column(String(255), nullable=False)
  created_at      = Column(TIMESTAMP, nullable=False, server_default=func.now())
  updated_at      = Column(DateTime, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))

在mariadb的sqlalchemy文档中,建议从sqlalchemy本身导入文本,并使用文本设置server_default,插入自定义命令。

updated_at=Column(DateTime, server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"))

要理解func。现在可以阅读SQL alchemy文档了。

希望我能帮上忙。

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

您可能需要使用onupdate=datetime。现在,以便UPDATEs也改变last_updated字段。

对于python执行的函数,SQLAlchemy有两个默认值。

默认设置INSERT的值,只设置一次 onupdate也将值设置为UPDATE上的可调用结果。

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