Is there a way in SQLAlchemy to do cross-database joins. To be specific, here is my use case:
Schema
- db1.entity1
- entity1_id: Primary Key
- entity2_id: Foreign Key to db2.entity2.entity2_id
- db2.entity2
- entity2_id: Primary Key
Model
I’m using declarative style for models.
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)
Now, as expected, my queries for Entity1 is failing with MySQL error messages saying table entity2 not found. I tried many different combination for __tablename__ with no success. So i was wondering if it is possible in SQLAlchemy.
You probably need to pass the
schemaparameter tosqlalchemy.schema.Table. When using declarative base for ORM mapping, you can provide this extra parameter through the__table_args__property on your classes.