SQLAlchemy中是否有一种方法可以进行跨数据库连接。具体来说,这是我的用例:
架构
- db1.entity1
- entity1_id:主键
- entity2_id:db2.entity2.entity2_id的外键
- db2.entity2
- 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')
你可能需要通过 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')