It took me a while, but I figured out how to use SQLAlchemy to model a relationship across two different kinds of databases:

    Base = declarative_base()

    class Survey(Base):
        __tablename__ = 'SURVEY'
    
        survey_id = Column("SURVEY_ID", Integer, primary_key=True)
        term_id = Column("TERM_ID", Integer, nullable=False)
        
        # Because the TERM table is in Oracle, but the SURVEY table is in
        # MySQL, I can't rely on SQLAlchemy's ForeignKey.  Thus,
        # I need to specify the relationship entirely by hand, like so:
        term = relationship("Term",
            primaryjoin="Term.term_id==Survey.term_id",
            foreign_keys=[term_id],
            backref="surveys"
        )
        
    class Term(Base):
        __tablename__ = 'TERM'
        
        term_id   = Column(Integer, primary_key=True)
        term_name = Column(String(30))
        start_date = Column(Date)
        end_date = Column(Date)
    
    mysql_engine = create_engine(MYSQL)
    oracle_engine = create_engine(ORACLE)
    
    Session = scoped_session(sessionmaker(
        binds={
            Term: oracle_engine,
            Survey: mysql_engine
        }
    ))
    
    if __name__ == "__main__":
        survey = Session.query(Survey).filter_by(survey_id=8).one()
        print survey.term
        print survey.term.surveys

I have to do this because the TERM table is in an Oracle database on which I only have read access, and I'm writing an app that records surveys, taken by students, about that term.

The above works, but it's very fragile when the number of tables climbs up, as the Session needs to specify exactly which mapped classes correspond to which engine. I would really like to be able to use a different Base to define which tables belong to which engine, instead of binding each table individ

Edit
Report