使用Queryset API按组计算总和

时间:2018-08-12 07:36:29

标签: django

我有这样一个下表:

MySQL [distributor]> select * from orderitems;
+-----------+------------+---------+----------+------------+
| order_num | order_item | prod_id | quantity | item_price |
+-----------+------------+---------+----------+------------+
|     20005 |          1 | BR01    |      100 |       5.49 |
|     20005 |          2 | BR03    |      100 |      10.99 |
|     20006 |          1 | BR01    |       20 |       5.99 |
|     20006 |          2 | BR02    |       10 |       8.99 |
|     20006 |          3 | BR03    |       10 |      11.99 |
|     20007 |          1 | BR03    |       50 |      11.49 |
|     20007 |          2 | BNBG01  |      100 |       2.99 |
|     20007 |          3 | BNBG02  |      100 |       2.99 |
|     20007 |          4 | BNBG03  |      100 |       2.99 |
|     20007 |          5 | RGAN01  |       50 |       4.49 |
|     20008 |          1 | RGAN01  |        5 |       4.99 |
|     20008 |          2 | BR03    |        5 |      11.99 |
|     20008 |          3 | BNBG01  |       10 |       3.49 |
|     20008 |          4 | BNBG02  |       10 |       3.49 |
|     20008 |          5 | BNBG03  |       10 |       3.49 |
|     20009 |          1 | BNBG01  |      250 |       2.49 |
|     20009 |          2 | BNBG02  |      250 |       2.49 |
|     20009 |          3 | BNBG03  |      250 |       2.49 |
+-----------+------------+---------+----------+------------+
18 rows in set (0.070 sec)

每个订单的total_price可以使用原始SQL来计算;

MySQL [distributor]> select order_num, sum(quantity*item_price) as total_price
    -> from orderitems
    -> group by order_num
    -> order by total_price;
+-----------+-------------+
| order_num | total_price |
+-----------+-------------+
|     20008 |      189.60 |
|     20006 |      329.60 |
|     20005 |     1648.00 |
|     20007 |     1696.00 |
|     20009 |     1867.50 |
+-----------+-------------+
5 rows in set (0.041 sec)

我想使用Django ORM完成它,
检查Queryset API文档后,我发现sum,但未找到“组”。

如何使用Django Queryset完成任务?

1 个答案:

答案 0 :(得分:2)

您可以结合使用GROUP BY.values(..)来执行.order_by(..)

from django.db.models import F, Sum

OrderItems.objects.values('order_number').annotate(
    total_price=Sum(F('quantity') * F('item_price'))
).order_by('order_number')

这将返回一个QuerySet,其中包含各有两个键的字典:'order_item'和'total_price'`。例如:

<QuerySet [{'order_item': 20005, 'total_price': 1648.00},
           {'order_item': 20006, 'total_price': 329.60},
           {'order_item': 20007, 'total_price': 1696.00},
           {'order_item': 20008, 'total_price': 189.60},
           {'order_item': 20009, 'total_price': 1867.50}]>
  

注意:通常,Django中模型的名称为单数,因此OrderItem而非OrderItems