簡體   English   中英

為什么 sqlalchemy 結果字典忽略 text() 列?

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

我正在嘗試新的 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}

有沒有辦法讓 dict 的結果包含文本列?

我對在 python 中聚合結果不感興趣:我想在 postgresql 中聚合。

如果要使用文本片段,請使用literal_column而不是text

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

您還可以使用 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