从SQLAlchemy Core中的函数调用中选择列 [英] Select columns from function call in sqlalchemy core
问题描述
在PostgreSQL中,我从my_function()中选择选择col1,col2。如何在sqlalchemy核心中做到这一点?
In postgresql I have select col1, col2 from my_function()
. How can I do that in sqlalchemy core?
select(func.my_function())
给出结果为字符串,但我需要一个元组。
select(func.my_function())
gives the result as a string, but I want a tuple.
推荐答案
您将要使用 FunctionElement.alias()
和轻量级 column()
:
You'll want to use FunctionElement.alias()
and the light weight column()
:
from sqlalchemy import func, select, column
stmt = select([column('col1'), column('col2')]).\
select_from(func.my_function().alias())
文档特别提到了Postgresql作为此构造的用例。上面的结果产生:
The documentation specifically mentions Postgresql as a use case for this construct. The above produces:
SELECT col1, col2
FROM my_function() AS anon_1
使用 column()
的参数 _selectable 也可以:
In [4]: fn = func.my_function().alias()
In [5]: stmt = select([column('col1', _selectable=fn),
...: column('col2', _selectable=fn)])
In [6]: print(stmt)
SELECT anon_1.col1, anon_1.col2
FROM my_function() AS anon_1
,但由于未记录 _selectable ,所以这可能不是一个好主意。
but since _selectable is left undocumented, this might not be a good idea.
这篇关于从SQLAlchemy Core中的函数调用中选择列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!