gpt4 book ai didi

postgresql - 在 sqlalchemy orm 中定义模式名称和约束

转载 作者:行者123 更新时间:2023-12-05 09:36:49 25 4
gpt4 key购买 nike

我正在尝试在 SQLAlchemy ORM 中创建一个表,我需要在其中指定模式名称(对于 postgres)和一些约束。要仅指定架构名称,可以使用字典:

class NewTable(Base):
__tablename__ = "new_table"
__table_args__ = {"schema": "schema_name"}

id = Column(Integer, primary_key=True)
name = Column(String(255), unique=True)

为了仅定义约束,代码将是:

class NewTable(Base):
__tablename__ = "new_table"

id = Column(Integer)
name = Column(String(255))

__table_args__ = (
PrimaryKeyConstraint("id", name="id_pk"),
UniqueConstraint("name")
)

,使用元组。

有人知道如何使用元组语法在最后一个代码块中设置架构名称吗?

最佳答案

我在文档中找到了答案:

https://docs.sqlalchemy.org/en/14/orm/declarative_tables.html#orm-declarative-table-configuration

基本上,所有关键字参数都必须设置在约束元组的末尾:

class NewTable(Base):
__tablename__ = "new_table"

id = Column(Integer)
name = Column(String(255))

__table_args__ = (
PrimaryKeyConstraint("id", name="id_pk"),
UniqueConstraint("name"),
{"schema": "schema_name"}
)

关于postgresql - 在 sqlalchemy orm 中定义模式名称和约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64911247/

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