16

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のクエリは失敗し、テーブルentity2が見つからないというMySQLエラーメッセージが表示されます。私は多くの異なる組み合わせを試しまし__tablename__たが、成功しませんでした。だから私はSQLAlchemyでそれが可能かどうか疑問に思いました。

4

1 に答える 1

23

おそらく、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')
于 2011-06-22T02:04:25.720 に答える