I am trying to do a query using SQL Alchemy, but I want to "select" 20 columns from a table that contains around 57, I know that the method to do this is
session.query(Table.col1, Table.col2, Table.col3, Table.col4......).all()
But it is so inefficient and for sure there is a much better way for doing this.
What I have tried unsuccessfully, but it is getting very close is:
# "columns" is a dictionary that contains all the column names, it looks more or less like this (shorter version
columns = {"Account ID": "AR3",
"Account Origination Month": "AR55",
"Origination balance": "AR66",
"Product": "AR10",
"Repayment Type": "AR69",
"Original Loan Term (in months)": "AR61",
"Initial Product Term (in months)": "AR106",
"Initial rate/margin": "AR109",
"Initial Rate Type": "AR107",
"Reversion margin": "AR119",}
columns_sqla = ", ".join(["Table."+str(value) for key, value in columns.items()])
>>> columns_sqla
'BoE.AR3, BoE.AR55, BoE.AR66, BoE.AR10, BoE.AR69, BoE.AR61, BoE.AR106, BoE.AR109, BoE.AR107, BoE.AR119'
Then I do:
session.query(columns_sqla)
But it throws an error because it is a string and it doesn't recognise it.
You can try variable unpacking mechanism as mentioned below:
session.query(*columns.values()).all()
Also run the below code for more understating.
Tuple = lambda *args: args
Dict = lambda **kwargs: kwargs
Print(Tuple(*columns))# PRINT KEYS
Print(columns.Keys())# PRINT KEYS
Print(Dict(**columns))# PRINT DICT ITEMS
Print(columns)# PRINT DICT ITEMS
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.