python Django - 将SQL查询转换为ORM查询(子查询)

时间:2017-12-30 12:35:11

标签: python mysql django orm

SELECT *,
        (SELECT sum(amount) FROM history
         WHERE history_id IN
                        (SELECT history_id FROM web_cargroup
                         WHERE group_id = a.group_id) AND type = 1)
        as sum
          FROM web_car a;

将上述查询转换为orm非常困难 1. orm annotate由group by自动创建。 2.将子查询置于“处于”状态

是很困难的

请帮忙。

1 个答案:

答案 0 :(得分:0)

如果我理解您提供的模型,这应该可行

from django.db.models import Sum

History.objects.filter(
    type=1,
    id__in=(CarGroup.objects.values('history_id'))
).aggregate(
    total_amount=Sum('amount')
)