简体   繁体   English

为什么 sqlalchemy 结果字典忽略 text() 列?

[英]Why sqlalchemy result dict ignores text() columns?

I'm trying the new sqlalchemy 1.4 select() syntax, but when executing this simple query, the result dict misses the column 'graph', but the result list includes it.我正在尝试新的 sqlalchemy 1.4 select() 语法,但是在执行这个简单的查询时,结果字典错过了“图表”列,但结果列表包含它。

import sqlalchemy as sa
from source.Models import Quadrant, Graph

engine = sa.create_engine("postgresql://blahblahblah")

dbsession = sa.orm.Session(engine)

stmt = sa.select(
    Quadrant.id,
    sa.text("jsonb_agg(graph.data order by graph.id) as graphs")
).outerjoin(
    Graph, Quadrant.id == Graph.quadrant_id
).group_by(
    Quadrant.id
)

with dbsession.begin():
    res = dbsession.execute(stmt)
    for r in res:
        print(r.keys())   # -> ['id'] **no graphs here!**
        print(list(r))    # -> [0, {aggregated data}]
        print(r[1])       # -> {aggregated data}

Is there a way to let the result as dict includes the text column?有没有办法让 dict 的结果包含文本列?

I'm not interested in aggregating the result in python: I want to aggregate in postgresql.我对在 python 中聚合结果不感兴趣:我想在 postgresql 中聚合。

Use literal_column instead of text , if you want to use the text fragment:如果要使用文本片段,请使用literal_column而不是text

sa.literal_column("jsonb_agg(graph.data order by graph.id)").label("graph")

You can also produce the expression using SQLA constructs:您还可以使用 SQLA 构造生成表达式:

from sqlalchemy.dialects.postgresql import aggregate_order_by

sa.func.jsonb_agg(aggregate_order_by(Graph.data, Graph.id)).label('graph')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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