【问题标题】:SQLAlchemy ForeignKey with dynamic PostgreSQL Schema具有动态 PostgreSQL 架构的 SQLAlchemy ForeignKey
【发布时间】:2020-10-08 14:12:43
【问题描述】:

如何使用声明式 ORM 将 SqlAlchemy 动态模式转换与外键关系一起使用?下面是一个示例,说明我正在尝试为多租户数据库(每个“用户”映射到模式)做些什么。我不确定如何在 SQLAlchemy 中设置 ForeignKey 约束

假设如下表声明:

class BaseMixin():
    __table_args__ = {'schema':'dynamic'}

class Image(Base, BaseMixin):
    __tablename__ == 'image'    
    id = Column(Integer, primary_key=True, autoincrement=True)

class Point(Base, BaseMixin):
    __tablename__ == 'point'
    fk = Column(Integer, ForeignKey("image.id", ondelete="CASCADE"))

Point 表与 Image 表具有 FK 关系。尝试查询这些表时出现以下错误:

NoReferencedTableError: Foreign key associated with column 'point.fk' could not find table 'image' with which to generate a foreign key to target column 'id'

会话参数化如下:

session.connection(execution_options={
                    "schema_translate_map": {"dynamic": "my_custom_schema"}})

从文档看来,会话上的 schema_translate_map 更新应该将 dynamic 替换为用户的架构。奇怪的是,表实例化正在按预期进行。尝试查询时弹出错误。

【问题讨论】:

    标签: python-3.x postgresql sqlalchemy


    【解决方案1】:

    您可能需要在 ForeignKey 中指定架构,即更新:

        fk = Column(Integer, ForeignKey("image.id", ondelete="CASCADE"))
    

    到:

        fk = Column(Integer, ForeignKey("dynamic.image.id", ondelete="CASCADE"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-10
      • 1970-01-01
      • 2021-09-11
      • 2021-08-16
      • 2012-09-22
      • 1970-01-01
      • 1970-01-01
      • 2015-08-08
      相关资源
      最近更新 更多