【问题标题】:Telling SqlAlchemy to map a column but not insert or update its values告诉 SqlAlchemy 映射列但不插入或更新其值
【发布时间】:2018-08-01 11:08:22
【问题描述】:

我的数据库中有由数据库管理的列。我希望 SqlAlchemy 映射这些并在读取操作中检索它们的值,但在创建或更新操作中不向它们发送任何内容,因为数据库本身管理这些。我该如何做到这一点?以下是详细信息:

这是我的 SQL Server ddl:

create table "foo" (
    "id" int identity not null primary key,
    "name" varchar(40) not null, 
    "whenCreated" datetime2(7) not null default (SYSUTCDATETIME()),
    "rowVersion" rowversion)

运行 sqlacodegen 生成:

class Foo(Base):
    __tablename__ = 'foo'

    id = Column(Integer, primary_key=True)
    name = Column(String(40, 'SQL_Latin1_General_CP1_CI_AS'), nullable=False, unique=True)
    whenCreated = Column(DateTime, nullable=False, server_default=text("(sysutcdatetime())"))
    rowVersion = Column(TIMESTAMP, nullable=False)

运行此代码:

session = Session()
def test(self):
    #create foo
    f = Foo(name='test')
    Test_crud.session.add(f)
    Test_crud.session.commit()

抛出以下异常:

sqlalchemy.exc.IntegrityError: (pyodbc.IntegrityError) ('23000', '[23000] [Microsoft][SQL Server Native Client 11.0][SQL Server]不能 将显式值插入时间戳列。将 INSERT 与 列列表以排除时间戳列,或将 DEFAULT 插入 时间戳列。 (273) (SQLExecDirectW); [23000] [微软] [SQL Server Native Client 11.0][SQL Server]Statement(s) could not be 准备好了。 (8180)') [SQL: 'INSERT INTO [foo] (name, [rowVersion]) 输出插入.id 值(?,?)'] [参数:('测试',无)] (此错误的背景:http://sqlalche.me/e/gkpj

我试过用这两种方式修改python对象,还是报同样的错误。

rowVersion = Column(TIMESTAMP, nullable=True)
rowVersion = Column(TIMESTAMP)

【问题讨论】:

    标签: python sql-server orm sqlalchemy


    【解决方案1】:

    根据以下Documentation page 和错误消息的这部分 (or insert a DEFAULT into the timestamp column),您可以执行以下操作:

    rowVersion = Column(TIMESTAMP(), default=text('DEFAULT'))
    

    【讨论】:

    • 谢谢!这不起作用,但这样做了:rowVersion = Column(TIMESTAMP(), server_default=text('DEFAULT'))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 2013-06-20
    • 2015-06-18
    • 2011-12-14
    • 1970-01-01
    • 2022-07-01
    • 1970-01-01
    相关资源
    最近更新 更多