【发布时间】:2022-01-07 08:07:53
【问题描述】:
使用 SQLAlchemy 异步 ORM 1.4、Postgres 后端、Python 3.7
我在 SA ORM 中使用augmented Declarative Base。这些表不在models.py 中,而是通过解析包含所有表模式的 JSON 脚本直接提交到数据库。因此,我无法导入脚本顶部的模型,例如 from models import ThisTable。
所以要对表进行 CRUD 操作,我首先通过反映元数据来检索它们。
以“通常”的方式,在脚本顶部导入所有表时,这样的查询会起作用:
result = await s.execute(select(func.sum(TableName.column)))
curr = result.all()
当我尝试从元数据中反映表和列对象以查询它们时,这不起作用。有很多AttributeError: 'Table' object has no attribute 'func' 或TypeError: 'Table' object is not callable错误。
def retrieve_table_obj(table):
meta = MetaData()
meta.reflect(bind=sync_engine)
return meta.tables[table]
def retrieve_table_cols(self, table):
table = retrieve_table_obj('users')
return table.columns.keys()
async def reading(collection, modifications):
table = db.retrieve_table_obj(collection)
columns = db.retrieve_table_cols(collection)
for c in columns:
for f in mods['fields']:
if c in f:
q = select(func.sum(table.c))
result = await s.execute(q)
curr = result.all()
asyncio.run(reading("users", {'fields': ["usage", "allowance"]}))
第一次必须显式检索数据库中的表和列时,如何查询它们?
【问题讨论】:
-
您可以使用 automap 扩展通过反射构建模型。
-
感谢自动地图的建议!它适用于同步引擎,但我正在使用异步引擎并且无法让 automap 使用它,即使在获取引擎连接并使用 conn.run_sync 调用函数时也是如此。您是否成功地将自动映射与异步引擎实例一起使用?
标签: postgresql sqlalchemy orm python-3.7