2016-04-29 51 views
1

列我有查詢:如何更換SQLAlchemy的查詢

q = Session.query(func.array_agg(Order.col)) 

已編譯的查詢將是:

SELECT array_agg(order.col) FROM orders 

我要動態地替換現有列。替換查詢後必須是:

SELECT group_concat(orders.col) FROM orders 

我必須使用會話和模型。我不必使用SQLAlchemy核心。我不必使用子查詢。當然,還可以有其他一些列,但我只需要替換一個。我試圖用column_descriptions屬性替換對象,我試圖用q.selectable.replace(或類似的東西,對不起,但我不記得正確的名字),我沒有得到正確的結果。

回答

1

正確的方法更換色譜柱實體:

q = Session.query(func.array_agg(Order.col)) 

q.with_entities(func.group_concat(Order.col)) 

SELECT group_concat(orders.col) FROM orders 
1

您可以query._entities列表

from sqlalchemy import func 
from sqlalchemy.orm.query import _ColumnEntity 

q = db.session.query(func.array_agg(Order.col)) 

print q 
>> SELECT array_agg("order".col) AS array_agg_1 FROM "order" 

new_entity = _ColumnEntity(q, func.group_concat(Order.col)) 
q._entities[0] = new_entity 

print q 
>> SELECT group_concat("order".col) AS group_concat_1 FROM "order"