2015-04-03 30 views
0

我使用的(優秀)Peewee ORM我的查詢需要在Python,我現在想下面的查詢轉換:如何將這個查詢轉換成Peewee ORM?

select t1.created, t1.property_id, t1.requesting_user_id, t1.type, t1.response 
from pdr t1 
inner join (
    select max(id) as id, property_id, requesting_user_id 
    from pdr 
    where property_id = 7 
    group by requesting_user_id 
) as t2 on t2.id = t1.id 

於是我想出了以下內容:

PDR.select()\ 
    .join(PDR)\ 
    .where(PDR.property == 7)\ 
    .group_by(PDR.requesting_user) 

但這創建了以下SQL:

SELECT t1.id, t1.created, t1.property_id, t1.requesting_user_id, t1.type, t1.comment, t1.responding_user_id, t1.property_details_request_id, t1.response 
FROM pdr AS t1 
INNER JOIN pdr AS t1 
ON (t1.property_details_request_id = t1.id) 
WHERE (t1.property_id = 7) 
GROUP BY t1.requesting_user_id 

我試過了其他一些變化,但我有點卡住了。

有誰知道我可以如何將我的查詢轉換成Peewee?歡迎所有提示!

回答

1

試試下面的(未經測試,但希望有用):

PDRAlias = PDR.alias() 
subq = (PDRAlias 
     .select(fn.MAX(PDRAlias.id).alias('max_id'), PDRAlias.property, PDRAlias.requesting_user) 
     .where(PDRAlias.property == 7) 
     .group_by(PDRAlias.requesting_user) 
     .alias('subq')) 
query = (PDR 
     .select() 
     .join(subq, on=(subq.c.max_id == PDR.id))) 
+0

感謝您的建議。我試了一下,現在我收到一條消息,說'OperationalError:沒有這樣的列:subq.id'。如果你想我可以給你一個整個回溯的pastebin。任何想法現在可能是錯誤的? – kramer65 2015-04-03 15:31:23

+0

您是否在'subq'定義的末尾包含'.alias('subq')'? – coleifer 2015-04-03 18:42:48

+0

哦,等等,我明白了,我會盡快編輯答案。 – coleifer 2015-04-03 18:43:16

相關問題