Automap 使用 sqlalchemy 反映 postgres 模式中的表

Automap reflect tables within a postgres schema with sqlalchemy

我正在关注使用 automap 反映数据库表的 sqlalchemy 文档:http://docs.sqlalchemy.org/en/latest/orm/extensions/automap.html#generating-mappings-from-an-existing-metadata

当我没有指定模式,而 Postgres 使用默认的 public 模式时,这按预期工作,我找到了我的表的名称:

>>> m = MetaData()
>>> b = automap_base(bind=engine, metadata=m)
>>> b.prepare(engine, reflect=True)
>>> b.classes.keys()
['ads', 'spatial_ref_sys', 'income']

但是当我指定一个显式模式时,我无法再访问 Base.classes 中的表。

>>> m = MetaData(schema='geography')
>>> b = automap_base(bind=engine, metadata=m)
>>> b.prepare(engine, reflect=True)
>>> b.classes.keys()
[]

尽管元数据正确反映:

>>> b.metadata.tables
immutabledict({geography.usa_cbsa_centroids': Table('usa_cbsa_centroids', MetaData(bind=Engine(postgresql://asteroids:***@localhost:5432/asteroids)), Column('GEOID', VARCHAR(length=5), table=<u
sa_cbsa_centroids>, nullable=False), ...})

请注意,表和列仅在运行时已知。

答案是SQLAlchemy 中的数据库table 需要主键,而我的table 没有。此页面上有其他信息:http://docs.sqlalchemy.org/en/latest/faq/ormconfiguration.html#how-do-i-map-a-table-that-has-no-primary-key.

The SQLAlchemy ORM, in order to map to a particular table, needs there to be at least one column denoted as a primary key column; multiple-column, i.e. composite, primary keys are of course entirely feasible as well. These columns do not need to be actually known to the database as primary key columns, though it’s a good idea that they are. It’s only necessary that the columns behave as a primary key does, e.g. as a unique and not nullable identifier for a row.

感谢 Michael Bayer 在 sqlalchemy 邮件列表上回答这个问题:https://groups.google.com/forum/#!topic/sqlalchemy/8F2tPkpR4bE