Django通过子查询注释

时间:2019-01-10 15:28:08

标签: python django

我正在努力进行聚合,我想做的是对子查询执行一些总和。 让我们假设以下模型:

+------------------------+-----------+
| Column                 |    Type   |
+------------------------+-----------+
| customer               |     fk    |
+------------------------+-----------+
| total                  |   float   |
+------------------------+-----------+
| somefield              | charfield |
+------------------------+-----------+
| issued_on              |    date   |
+------------------------+-----------+
| validation_status_code | charfield |
+------------------------+-----------+

子查询如下:

Invoice.objects.filter(customer_id=4).order_by('issued_on')[:48+1]

这仅是客户发票的一半,此处的想法是获取一段时间内的汇总(这是子查询)。

假设我要获取总计的总和,如果状态为“错误”并且以“ somefield”为依据,则总计的总和,

我已经弄清楚了SQL查询(它在mysql上),我想知道是否可以通过Django ORM做到这一点。

查询如下:

SELECT 
table1.somefield,
SUM(table1.total) AS total_clean,
SUM(CASE
    WHEN table1.validation_status_code = 'error' THEN table1.total
    ELSE NULL
END) AS canceladas,
(SUM(table1.total) - SUM(CASE
    WHEN table1.validation_status_code = 'error' THEN table1.total
    ELSE NULL
END)) AS ventas
FROM
(SELECT 
        invoice.id,
        invoice.customer_id,
        invoice.total,
        invoice.somefield,
        invoice.validation_status_code,
        invoice.issued_on,
FROM
    invoice
WHERE
    invoice.customer_id = 4
ORDER BY invoice.issued_on ASC
LIMIT 49) AS table1
GROUP BY table1.somefield

0 个答案:

没有答案