【问题标题】:Define both schema name and constraint in sqlalchemy orm在 sqlalchemy orm 中定义模式名称和约束
【发布时间】:2020-11-19 20:05:44
【问题描述】:

我正在尝试在 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")
    )

,使用元组。

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

【问题讨论】:

    标签: postgresql sqlalchemy


    【解决方案1】:

    我在文档中找到了答案:

    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"}
        )
    

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 1970-01-01
      • 2014-02-27
      • 2019-03-06
      • 1970-01-01
      • 2015-04-29
      • 2014-10-08
      • 1970-01-01
      • 2022-01-22
      相关资源
      最近更新 更多