将列动态传递给 python postgresql 中的 select()

dynamically pass the columns to select() in python postgresql

下面的代码工作正常

table = Table('user_data',metadata,autoload=True,autoload_with=conn)
stmt = select([table.columns.user_id,table.columns.username])
results = conn.execute(stmt).fetchall()
print(results)

但是当我尝试将列作为列表(来自 postresql 数据库)传递时,它失败了

cols = get_table_cols() -- it returns a list -> [table.columns.user_id,table.columns.username]
stmt = select(cols )
results = conn.execute(stmt).fetchall()
print(results)

错误:

 sqlalchemy.exc.ArgumentError: Textual column expression 'table.c.username' should be explicitly declared with text('table.c.username'), or use column('table.c.username') for more specificity

请就此提供意见

我最近刚经历过类似的事情。请记住,我的引擎已将 'Future' 属性设置为 True(如果这对您不起作用)

我不记得为什么像这样简单地解包列表不起作用(在你的情况下可能是这样)

stmt = select(*cols)

但这最终成为我的解决方案

cols = get_table_cols()
#assuming cols does return a list
stmt = select(*[c for c in cols])

#alternatively you can get the columns directly from the table object
#stmt = select(*[c for c in table.c])
results = conn.execute(stmt).fetchall()

#session.execute(stmt).all() -> what I did for ORM

print(results)

如果您对 ORM 使用声明式 类,则可以使用

访问 table 对象
ClassName.__table__