我有幾個函數需要使用count(),group_by和order_by進行一對多連接。我使用sqlalchemy.select函數來產生一個查詢,該查詢將返回一組id,然後我將迭代在單個記錄上進行ORM選擇。我想知道的是,如果有一種方法可以在單個查詢中使用ORM來完成我需要的操作,那麼我可以避免必須執行迭代。SQLAlchemy with count,group_by和order_by使用ORM
下面是我現在正在做的一個例子。在這種情況下,實體是位置和指南,映射爲一對多。我試圖根據與他們有關的指南排序排名的頂部位置。
def popular_world_cities(self):
query = select([locations.c.id, func.count(Guide.location_id).label('count')],
from_obj=[locations, guides],
whereclause="guides.location_id = locations.id AND (locations.type = 'city' OR locations.type = 'custom')",
group_by=[Location.id],
order_by='count desc',
limit=10)
return map(lambda x: meta.Session.query(Location).filter_by(id=x[0]).first(), meta.engine.execute(query).fetchall())
解決方案
我發現做到這一點的最好辦法。只需提供一個from_statement
而不是filter_by
或其他一些。像這樣:
meta.Session.query(Location).from_statement(query).all()
舉例在此處可能有用 – user890739 2015-10-23 18:25:17