Python 3.x 强制转换某些列并选择所有列,而不显式写入列名
我想强制转换一些列,然后选择所有其他列Python 3.x 强制转换某些列并选择所有列,而不显式写入列名,python-3.x,database,sqlalchemy,fastapi,Python 3.x,Database,Sqlalchemy,Fastapi,我想强制转换一些列,然后选择所有其他列 id, name, property, description = column("id"), column("name"), column("property"), column("description") select([cast(id, String).label('id'), cast(property, String).label('property'), name, description]).select_from(events_tabl
id, name, property, description = column("id"), column("name"), column("property"), column("description")
select([cast(id, String).label('id'), cast(property, String).label('property'), name, description]).select_from(events_table)
是否有任何方法可以强制转换某些列并选择全部而不提及所有列名称
我试过了
select([cast(id, String).label('id'), cast(property, String).label('property')], '*').select_from(events_table)
py_.transform(return_obj, lambda acc, element: acc.append(dict(element)), [])
但我得到了两个额外的列(总共7列),它们是强制转换的,我不能将它们转换为字典,因为字典会抛出键错误
我正在使用FASTAPI、sqlalchemy和数据库(异步)
谢谢你一定能做到
select_columns = []
for field in events_table.keys()
select_columns.append(getattr(events_table.c, field))
select(select_columns).select_from(events_table)
从该表中选择所有字段。您还可以保留一个要实际选择的字段列表,而不是events_table.keys(),如
谢谢,我找到了一个解决方法,events\u table是一个sqlalchemy.table,所以我必须执行events\u table.columns.keys()
column\u names=py\u.transform(list(events\u table.columns.keys()),lambda acc,value:acc.append(column(value)),如果value不在['id','property']else acc.append(cast(column(f'{value}'),String.label(f'{value}')),[])
然后运行查询query=select(column\u names)。从(main.app.events\u表)中选择
select_these = ["id", "name", "property", "description"]
select_columns = []
for field in select_these
select_columns.append(getattr(events_table.c, field))
select(select_columns).select_from(events_table)