python - 跨数据库加入sqlalchemy

标签 python sqlalchemy flask-sqlalchemy

SQLAlchemy 中有没有一种方法可以进行跨数据库连接。具体来说,这是我的用例:

架构

  1. db1.entity1
    1. entity1_id:主键
    2. entity2_id:db2.entity2.entity2_id 的外键
  2. db2.entity2
    1. entity2_id:主键

型号

我正在为模型使用声明式

class Entity1(Base):
  __tablename__ = 'entity1' ## I tried combination of <db>.<table> with no success
  entity1_id = Column(Integer, primary_key=True)
  entity2_id = Column(Integer, ForeignKey('db2.entity2.entity2_id'))
  entity2 = relationship('Entity2')

class Entity2(Base):
  __tablename__ = 'entity2' ## I tried combination of <db>.<table> with no success
  entity2_id = Column(Integer, primary_key=True)

现在,正如预期的那样,我对 Entity1 的查询失败了,MySQL 错误消息说找不到表 entity2。我为 __tablename__ 尝试了许多不同的组合,但没有成功。所以我想知道在 SQLAlchemy 中是否可行。

最佳答案

您可能需要将 schema 参数传递给 sqlalchemy.schema.Table。当为 ORM 映射使用声明性基础时,您可以通过类上的 __table_args__ 属性提供此额外参数。

class Entity2(Base):
    __tablename__ = 'entity2' ## I tried combination of <db>.<table> with no success
    __table_args__ = {'schema': 'db2'}
    entity2_id = Column(Integer, primary_key=True) 

class Entity1(Base):
    __tablename__ = 'entity1' ## I tried combination of <db>.<table> with no success
    __table_args__ = {'schema': 'db1'}
    entity1_id = Column(Integer, primary_key=True)
    entity2_id = Column(Integer, ForeignKey(Entity2.entity2_id))
    entity2 = relationship('Entity2')

关于python - 跨数据库加入sqlalchemy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6433592/

相关文章:

python - 添加由不同但重叠的间隔索引的两个系列

python - 使用 HybridProperty 组合日期和时间列并设置其格式

python - 用于非/NULL 值的 SQLAlchemy 过滤器 - 工作 - 但如何将它放在列表中?

Flask-admin 用户警告 : Fields missing from ruleset

python - Flask-sqlalchemy - 用户查询 'BaseQuery' 对象没有属性 'password'

python - Python 中的字符串到对象

javascript - 从 JS 向 Django 表单输入字段插入一个变量

python - 用于文章的超长文本的 SQLalchemy 类型

postgresql - 如何从 Python RDFLib 加速 SPARQL 查询?

python - 导入错误 : cannot import name 'ssl' from 'urllib3.util.ssl_'