请原谅任何术语错别字,对SQLite以外的数据库没有多少经验。我试图复制我在SQLite中所做的事情,在那里我可以将数据库连接到第二个数据库并在所有表中进行查询。我没有使用SQLAlchemy和SQLite
我在Win7 / 54上使用SQLAlchemy 1.0.13,Postgres 9.5和Python 3.5.2(使用Anaconda)。我使用postgres_fdw连接了两个数据库(在localhost上),并从辅助数据库导入了一些表。我可以用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())
并未列出附表(主数据库中的表确实显示)。有没有办法做我想要完成的事情?
答案 0 :(得分:1)
为了映射表SQLAlchemy needs there to be at least one column denoted as a primary key column。这并不意味着该列实际上需要成为数据库眼中的主键列,尽管这是一个好主意。根据您从外部模式导入表的方式,它可能没有主键约束的表示,或者任何其他约束。您可以通过 Table
实例中的overriding the reflected primary key column(不在映射的类主体中)解决此问题,或者更好地告诉映射器哪些列构成候选键:< / p>
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
}
要检查外部表名,请使用PGInspector.get_foreign_table_names()
方法:
print(insp.get_foreign_table_names())