2016-10-10 20 views
0

請原諒任何術語拼寫錯誤,除了SQLite之外沒有太多的數據庫經驗。我試圖複製我會在SQLite中做什麼,我可以將數據庫附加到第二個數據庫並跨所有表進行查詢。我沒有在SQLite上使用SQLAlchemySQLAlchemy沒有找到與postgres_fdw連接的Postgres表

我在Win7/54上使用SQLAlchemy 1.0.13,Postgres 9.5和Python 3.5.2(使用Anaconda)。我使用postgres_fdw連接了兩個數據庫(在本地主機上),並從輔助數據庫導入了一些表。我可以使用psycopg2手動成功地在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 columnPGInspector.get_foreign_table_names()方法:

print(insp.get_foreign_table_names()) 
+0

謝謝,它的工作。 – RunDeep