2011-06-22 7 views
11

SQLAlchemyでデータベース間の結合を行う方法はありますか?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のクエリは、テーブルエンティティ2が見つからないというMySQLエラーメッセージで失敗しています。私は__tablename__のために多くの異なる組み合わせを試してみました。だから、SQLAlchemyで可能かどうか疑問に思っていた。

答えて

14

おそらく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') 
+0

ありがとう@TokenMacGuy。 '__table_args__'が働きました。 – Vikas

関連する問題