【问题标题】:Calculate expanded_price using Django ORM使用 Django ORM 计算扩展价格
【发布时间】:2018-08-12 02:47:23
【问题描述】:

原始 SQL 将使用计算字段执行数学计算,例如:

item_price 列包含订单中每件商品的单价。要扩大商品价格(商品价格乘以订购数量),可以执行以下操作:

MySQL [distributor]> select prod_id, 
    -> quantity,
    -> item_price,
    -> quantity*item_price as expanded_price
    -> from orderitems
    -> where order_num = 20008;
+---------+----------+------------+----------------+
| prod_id | quantity | item_price | expanded_price |
+---------+----------+------------+----------------+
| RGAN01  |        5 |       4.99 |          24.95 |
| BR03    |        5 |      11.99 |          59.95 |
| BNBG01  |       10 |       3.49 |          34.90 |
| BNBG02  |       10 |       3.49 |          34.90 |
| BNBG03  |       10 |       3.49 |          34.90 |
+---------+----------+------------+----------------+
5 rows in set (0.027 sec)

我如何使用 Django ORM 完成此任务?

【问题讨论】:

  • 请添加您的 models.py

标签: django


【解决方案1】:

Django 提供annotate() 方法来注释结果。

from django.db.models import F

result = orderitems.objects.filter(order_num=20008).annotate(
    expanded_price=F('quantity') * F('item_price')
)

【讨论】:

    猜你喜欢
    • 2019-08-24
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多