1

简而言之,我想知道如何在 Django 中表达以下 SQL 查询

SELECT SUM(product.cost_price * product.markup_percentage) from product 
INNER JOIN shopping_cart on shopping_cart.product_id = product.id 
WHERE shopping_cart.user_id = <user_id>;

有一个 ShoppingCart 模型,它具有 FK 到 Product 模型。我正在尝试获取用户为其购物车中所有产品支付的总金额。

目前,向product表中添加另一列不是一种选择。

我知道我能做到

shopping_cart = ShoppingCart.objects.select_related('product').filter(user_id=<user_id>)

检索产品列表并在 python 代码中执行产品操作的总和。

Sumproduct 中使用 Django 的聚合建议的答案不像答案的评论中提到的那样起作用。

那么除了编写原始 SQL 查询或在 python 中进行计算之外,还有其他方法可以在 Django 中执行此操作吗?

4

1 回答 1

0

如果您将其更改为此,其他答案是否有效?

.extra(
    select={'actual_price': 'SUM(cost_price * markup_percentage)'},
).aggregate(total=Sum('actual_price'))['total']
于 2013-04-18T19:10:53.190 回答