Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-cloud-platform/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 高效查询多个列SQLAlchemy ORM_Python_Python 3.x_Orm_Sqlalchemy - Fatal编程技术网

Python 高效查询多个列SQLAlchemy ORM

Python 高效查询多个列SQLAlchemy ORM,python,python-3.x,orm,sqlalchemy,Python,Python 3.x,Orm,Sqlalchemy,我正在尝试使用SQL Alchemy进行查询,但我想从一个包含大约57列的表中“选择”20列,我知道这样做的方法是 session.query(Table.col1, Table.col2, Table.col3, Table.col4......).all() 但它是如此低效,而且肯定有更好的方法来实现这一点 我尝试过但没有成功,但离成功越来越近的是: # "columns" is a dictionary that contains all the column names, it lo

我正在尝试使用SQL Alchemy进行查询,但我想从一个包含大约57列的表中“选择”20列,我知道这样做的方法是

session.query(Table.col1, Table.col2, Table.col3, Table.col4......).all()

但它是如此低效,而且肯定有更好的方法来实现这一点

我尝试过但没有成功,但离成功越来越近的是:

# "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'

那么我会:

session.query(columns_sqla)


但它会抛出一个错误,因为它是一个字符串,无法识别它。

您可以尝试如下所述的变量解包机制:

session.query(*columns.values()).all()
还可以运行下面的代码以获得更多的低调

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

第一种方法效率如何?也许很麻烦,但它的性能应该很好。因为您不打算手动键入20列,所以效率很低,对吧?谢谢Prakash,这是一个非常有用的答案