【问题标题】:SQLAlchemy not finding Postgres table connected with postgres_fdwSQLAlchemy 找不到与 postgres_fdw 连接的 Postgres 表
【发布时间】:2016-10-10 04:16:20
【问题描述】:

请原谅任何术语拼写错误,对 SQLite 以外的数据库没有太多经验。我正在尝试复制我在 SQLite 中所做的事情,我可以将数据库附加到第二个数据库并查询所有表。我没有在 SQLite 中使用 SQLAlchemy

我在 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())

并且未列出附加的表(主数据库中的表确实显示)。有没有办法做我想要完成的事情?

【问题讨论】:

    标签: python postgresql sqlalchemy postgres-fdw


    【解决方案1】:

    为了映射表SQLAlchemy needs there to be at least one column denoted as a primary key column。这并不意味着该列实际上必须是数据库眼中的主键列,尽管这是一个好主意。根据您从外部模式导入表的方式,它可能没有主键约束或任何其他约束的表示形式。您可以通过 Table 实例(不在映射类正文中)中的 overriding the reflected 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
        }
    

    要检查外部表名,请使用PGInspector.get_foreign_table_names() 方法:

    print(insp.get_foreign_table_names())
    

    【讨论】:

      猜你喜欢
      • 2022-08-24
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 2011-11-25
      • 2020-03-26
      • 1970-01-01
      相关资源
      最近更新 更多