postgresql - Automap 使用 sqlalchemy 反射(reflect) postgres 模式中的表

标签 postgresql sqlalchemy psycopg2

我正在关注使用 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/

相关文章:

postgresql - Postgres 字符串比较特性

sql - postgresql 中的映射关系

python - SQLAlchemy 忽略查询中的特定字段

sql - 如何将 PostgreSQL 转储文件恢复到 Postgres 数据库中?

sqlalchemy - 将一个模型与单个关系中的多个其他模型相关联

Python - Redshift SQL 查询中的动态变量

Python eTree Parser 没有附加元素

linux - 无法使用 SSH 在共享服务器 (Linux) 上安装 psycopg2。说,错误: command 'gcc' failed with exit status 1

python - SQLAlchemy中的VALUES子句

python - 使用 Alembic 更改枚举字段