2008-12-16 38 views
3

我有幾個函數需要使用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() 

回答

0

我找到了最好的方法來做到這一點。只需提供一個from_statement而不是filter_by或其他一些。像這樣:

meta.Session.query(Location).from_statement(query).all() 
1

什麼你試圖做直接映射到SQLAlchemy的子查詢之間的連接和一張桌子[從當前選擇調用做出。您需要將次序從次選中移出,並用count(desc)創建一個單獨的帶標籤的列;爲該列的外部選擇命令。

除此之外,我沒有看到太多不明顯的東西。

1

夥計們,我發現這很難,但SQL Alchemy確實支持group_by。 Query下的文檔沒有這麼說,但它確實支持它 - 我已經使用它了!

而且,你也可以使用order_by。我打算像你一樣創建一個特殊的類/查詢,但後來發現有一個group_by()函數。

希望這會幫助別人!

+0

舉例在此處可能有用 – user890739 2015-10-23 18:25:17