使用Django ORM计算扩展价格

使用Django ORM计算扩展价格,django,Django,原始SQL将使用计算字段执行数学计算,例如: “项目价格”列包含订单中每个项目的单价。要展开项目价格(项目价格乘以订购数量),可以执行以下操作: MySQL [distributor]> select prod_id, -> quantity, -> item_price, -> quantity*item_price as expanded_price -> from orderitems -> where orde

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

“项目价格”列包含订单中每个项目的单价。要展开项目价格(项目价格乘以订购数量),可以执行以下操作:

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实现这一点?

Django提供了注释结果的方法

from django.db.models import F

result = orderitems.objects.filter(order_num=20008).annotate(
    expanded_price=F('quantity') * F('item_price')
)
请添加您的models.py