我正在关注使用 automap
反射(reflect)数据库表的 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()
[]
尽管元数据正确反射(reflect):
>>> 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 中的数据库表需要一个主键,而我的表没有。此页面上有其他信息: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
关于postgresql - Automap 使用 sqlalchemy 反射(reflect) postgres 模式中的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29905160/