【发布时间】:2015-05-28 07:30:20
【问题描述】:
我有一个表,我正在使用 SQLAlchemy 表达式引擎创建并与之交互,我需要能够从 ARRAY 列中获取值作为 python tuple 而不是 list。由于ARRAY 列的构造函数允许您指定是否要将值作为元组,我最终只是将表反映在数据库之外,寻找ARRAY 列,将它们替换为具有适当的关键字参数,然后使用它来构造表达式。像这样:
from sqlalchemy import Table, Column, String, MetaData, select
def swapArrayColumns(table):
new_cols = []
for col in table.columns:
if isinstance(col.type, ARRAY):
new_cols.append(Column(col.name, ARRAY(String, as_tuple=True)))
else:
new_cols.append(Column(col.name, col.type))
return new_cols
engine = create_engine('postgresql://localhost:5432/dbname')
meta = MetaData()
table = Table('table_name', meta, autoload=True, autoload_with=engine)
new_cols = swapArrayColumns(table)
# delete old meta since we are re-mapping table
del meta
meta = MetaData()
new_table = Table('table_name', meta, *new_cols)
# Now I can use the new table object to generate expressions
sel = select([new_table]).where(new_table.c.foo == 'bar')
rows = list(engine.execute(sel))
由于这被大量使用,我想知道是否有更优雅的方式来完成同样的事情,也许是通过创建一个自定义的 sqlalchemy 方言来为我做这件事。我真正想要的是我的ARRAY 列默认返回为python tuples。
【问题讨论】:
标签: python arrays postgresql sqlalchemy