gpt4 book ai didi

python - 如何在 SQLAlchemy 中为列插入数据库的默认值?

转载 作者:行者123 更新时间:2023-11-29 12:19:15 25 4
gpt4 key购买 nike

我正在尝试向 Postgresql 表中插入一行,如下所示:

CREATE TABLE launch_ids(
id SERIAL PRIMARY KEY,
launch_time TIMESTAMP WITHOUT TIME ZONE NOT NULL DEFAULT
(now() at time zone 'utc')
);

我的类(class)是这样的:

class LaunchId(Base):
"""Launch ID table for runs"""
__tablename__ = 'launch_ids'

id = Column(Integer, primary_key=True)
launch_time = Column(DateTime)

launch_time 应该由数据库管理。我知道可以使用 default=datetime.datetime.utcnow(),但这会使用客户端的当前时间。我知道可以使用 default=func.now(),但这意味着如果数据库的默认定义发生变化,那么我需要在两个地方更改默认值。

这是我尝试在 launch_ids 中插入一行而不指定值时得到的结果:

l = LaunchId()
session.add(l)
session.commit()

IntegrityError: (psycopg2.IntegrityError) null value in column "launch_time" violates not-null constraint
DETAIL: Failing row contains (1, null).
[SQL: 'INSERT INTO launch_ids (launch_time) VALUES (%(launch_time)s) RETURNING launch_ids.id'] [parameters: {'launch_time': None}]

最佳答案

使用FetchedValue:

from sqlalchemy.schema import FetchedValue

class LaunchId(Base):
...
launch_time = Column(DateTime, FetchedValue())

关于python - 如何在 SQLAlchemy 中为列插入数据库的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35606303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com