首页 > 解决方案 > 将 SQL 转换为 Django ORM 查询(“Lead”函数内“Window”内的“IF”语句)

问题描述

我正在尝试获取下一个开始使用服务的客户的日期,并将该日期附加到上一个客户。

我试图了解 F() 和 Q() 以及类似 SQL 的函数如何在 Django 中工作,但无法了解如何将以下 SQL 语句转换为有效的 Django 代码:

            SELECT
            *,
            LEAD(
                IF(actual_start IS NOT NULL, actual_start, planned_start)
                , 1)
                OVER(
                    PARTITION BY customer
                    ORDER BY actual_start, planned_start
                ) AS next_starting_time
            FROM builds_build;

我尝试将我看到的一些东西混合在一起:

    window = {
        "partition_by": [F('customer')],
        'order_by': [F('actual_start'),F('planned_start')]
    }
    records = Record.objects.annotate(
        next_customer = Window(
            expression = Lead(F('actual_start') if F('actual_start') else F('planned_start'),
             **window)
        )
    )

但是,查看查询,没有考虑 LEAD 表达式的条件部分(这是 Django 生成的 SQL 的样子):

            SELECT
            *,
            LEAD(actual_start, 1)
                OVER(
                    PARTITION BY customer
                    ORDER BY actual_start, planned_start
                ) AS next_starting_time
            FROM builds_build;

但是,它完全删除了预期的“IF”语句。任何提示和想法将不胜感激

标签: pythonsqldjango

解决方案


推荐阅读