【问题标题】:How to convert this query to the Peewee ORM?如何将此查询转换为 Peewee ORM?
【发布时间】:2015-04-03 08:38:35
【问题描述】:

我正在使用(优秀的)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

所以我想出了以下内容:

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 吗?欢迎所有提示!

【问题讨论】:

    标签: python mysql join orm 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)))
    

    【讨论】:

    • 感谢您的建议。我试过了,现在我收到一条消息说OperationalError: no such column: subq.id。如果您愿意,我可以为您提供整个回溯的粘贴箱。知道现在可能出了什么问题吗?
    • 您是否在subq 定义的末尾添加了.alias('subq')
    • 我认为问题是 JOIN 位于子查询中的“id”上,但未选择该列。相反,我们加入了 MAX(id),我将其别名为“max_id”并更新了连接谓词。现在应该可以工作了。
    • 太棒了,谢谢一百万!感谢您创建 Peewee,它真的很棒!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 2014-12-26
    • 2018-07-19
    • 2019-10-31
    • 2019-07-19
    • 2019-10-17
    • 2021-09-15
    相关资源
    最近更新 更多