简体   繁体   English

如何将此查询转换为Peewee ORM?

[英]How to convert this query to the Peewee ORM?

I'm using the (excellent) Peewee ORM for my query needs in Python and I now want to convert the following query: 我正在使用(优秀) Peewee ORM来满足我在Python中的查询需求,现在我想转换以下查询:

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

So I came up with the following: 因此,我提出了以下建议:

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

but this creates the following sql: 但这会创建以下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

I tried a couple other variations, but I'm kinda stuck. 我尝试了其他几种变体,但是有点卡住了。

Does anybody know how I can convert my query to Peewee? 有人知道如何将查询转换为Peewee吗? All tips are welcome! 欢迎所有提示!

Try the following (untested, but hopefully helpful): 尝试以下操作(未经测试,但希望会有所帮助):

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)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM