在SQLAlchemy中重新格式化查询结果

时间:2016-03-15 15:44:51

标签: python sql django orm sqlalchemy

SQL查询不仅允许获取一堆列,而且还可以同时将其形成为usefult。 E.g:

select Person.name + " likes " + Food.name as all_i_want_as_a_result from Food, Person where Food.id == Person.favourite_food

但是我怎么能用SQLAlchemy做同样的事情呢? E.g:

query = db.session.query(Food, Person).filter(Food.id == Person.favourite_food) <-- how do I modify this line?
for row in db.session.execute(query)
    print row

预期输出为:

Alice likes icecream
Bob likes pizza

1 个答案:

答案 0 :(得分:0)

您可以在.query()

中查询任意内容
query = db.session.query(Person.name.concat(" likes ").concat(Food.name).label("all_i_want_as_a_result"))
                  .filter(Food.id == Person.favourite_food)
print query

打印:

SELECT "Person".name || ? || "Food".name AS all_i_want_as_a_result 
FROM "Person", "Food" 
WHERE "Food".id = "Person".favourite_food