2016-10-10 13 views
0

用語のタイプミス、SQLite以外のデータベースに関する豊富な経験はありません。私はSQLiteで何をするかを再現しようとしています。データベースを2番目のデータベースにアタッチし、すべてのテーブルを問い合せることができます。私はSQLiteでSQLAlchemyを使用していませんでしたSQLAlchemyがpostgres_fdwに接続されたPostgresテーブルを見つけられない

私は、Win7/54でSQLAlchemy 1.0.13、Postgres 9.5、Python 3.5.2(Anacondaを使用)を使っています。 postgres_fdwを使用して2つのデータベース(ローカルホスト上)を接続し、セカンダリデータベースからいくつかのテーブルをインポートしました。 PgAdminIIIのSQLとpsycopg2を使ったPythonから、接続されたテーブルを正常にクエリできます。 SQLAlchemyので、私は試してみた:

# Same connection string info that psycopg2 used 
engine = create_engine(conn_str, echo=True) 

class TestTable(Base): 
    __table__ = Table('test_table', Base.metadata, 
         autoload=True, autoload_with=engine) 

    # Added this when I got the error the first time 
    # test_id is a primary key in the secondary table 
    Column('test_id', Integer, primary_key=True) 

とエラーが表示されます。

sqlalchemy.exc.ArgumentError: Mapper Mapper|TestTable|test_table could not 
assemble any primary key columns for mapped table 'test_table' 

それから私が試した:

insp = reflection.Inspector.from_engine(engine) 
print(insp.get_table_names()) 

および添付の表はから(テーブルが表示されていませんプライマリデータベースが表示されます)。私が達成しようとしていることをする方法はありますか?

答えて

1

テーブルをマップするためにSQLAlchemy needs there to be at least one column denoted as a primary key column。これは、データベースの目の中で実際に列が主キー列である必要があることを意味するものではありませんが、それは良い考えです。外部スキーマからテーブルをインポートした方法によっては、プライマリキー制約の表現や他の制約がないことがあります。

engine = create_engine(conn_str, echo=True) 

test_table = Table('test_table', Base.metadata, 
        autoload=True, autoload_with=engine) 

class TestTable(Base): 
    __table__ = test_table 
    __mapper_args__ = { 
     'primary_key': (test_table.c.test_id,) # candidate key columns 
    } 

外国テーブル名が使用検査する:あなたはTableインスタンス(ないマッピングされたクラス本体内)、またはいっその列が候補キーを含む、何マッパーを伝えるのいずれかoverriding the reflected primary key columnによってこの問題を回避することができますPGInspector.get_foreign_table_names()方法:

print(insp.get_foreign_table_names()) 
+0

ありがとうございます。 – RunDeep

関連する問題