在python-postgresql中动态地将列传递给select()



以下代码运行良好

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)

但是,当我尝试将列作为列表(来自postresqldb(传递时,失败了

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使用声明性类,则可以使用来访问表对象

ClassName.__table__

最新更新