2016-10-10 2 views
0

어떤 오타도 용서해주십시오. SQLite 이외의 데이터베이스에 대한 경험이 많지 않습니다. 데이터베이스를 두 번째 데이터베이스에 연결하고 모든 테이블에서 쿼리 할 수있는 SQLite에서 수행 할 작업을 복제하려고합니다. SQLite로 SQLAlchemy를 사용하지 않았습니다.SQLAlchemy가 postgres_fdw와 연결된 Postgres 테이블을 찾지 못했습니다.

저는 Win7/54에서 SQLAlchemy 1.0.13, Postgres 9.5 및 Python 3.5.2 (Anaconda 사용)와 함께 작업하고 있습니다. postgres_fdw를 사용하여 두 개의 데이터베이스 (로컬 호스트에 있음)를 연결하고 보조 데이터베이스에서 몇 개의 테이블을 가져 왔습니다. PgAdminIII의 SQL과 psycopg2를 사용하는 Python을 사용하여 연결된 테이블을 성공적으로 쿼리 할 수 ​​있습니다. (로부터 테이블을

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

및 첨부 된 테이블이 나열되지 않은 : 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' 

을 나는 시도 기본 데이터베이스가 표시됩니다). 내가 성취하려는 일을 할 수있는 방법이 있습니까?

답변

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

관련 문제