简体   繁体   中英

Programmatically rename multiple columns in query using SqlAlchemy

I have a query where I am joining multiple tables and selecting all the columns. I would like to suffix each column in the result with the name of the table it came from. Is there a way to programmatically do this in SqlAlchemy?

Assuming your question is related to the other one ( Sqlalchemy dynamically create joins ), here you go (I am extending accepted answer):

s_stmt = [
    col.label(col.name + '_' + ti.name)
    for ti in t for col in ti.columns
]

t_joined = t[0]
for ti in t[1:]:
    t_joined = t_joined.join(ti, ti.c.id == t[0].c.id, full=False)


result = select(s_stmt).select_from(t_joined)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM