【问题标题】:Cross database join in sqlalchemysqlalchemy 中的跨数据库连接
【发布时间】:2011-09-19 23:42:07
【问题描述】:

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 中是否有可能。

【问题讨论】:

标签: python sqlalchemy flask-sqlalchemy


【解决方案1】:

您可能需要将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')

【讨论】:

  • 如果您遇到此问题并且正在使用 SQL Server,请注意,您可以通过应用 __table_args__ = {'schema': 'db2.dbo'}(如果架构不是默认值,则替换 dbo)同时提供数据库和架构。更多信息:docs.sqlalchemy.org/en/13/dialects/…
猜你喜欢
  • 1970-01-01
  • 2014-07-08
  • 2018-05-15
  • 1970-01-01
  • 2011-08-16
  • 1970-01-01
  • 2011-03-25
  • 2019-03-03
相关资源
最近更新 更多