在Django中计算模型属性的总和

7

我有一个模型Order,其中有一个属性根据外键链接的OrderItem计算order_total

我想计算若干个Order实例的order_total属性之和。

是否有方法可以做到这一点?

class Order(models.Model):
    customer = models.ForeignKey(Customer)
    placed = models.DateField()

    ...

    def get_total_cost(self):
        return sum(item.get_cost() for item in self.items.all())

    order_total = property(get_total_cost)


class OrderItem(models.Model):
    order = models.ForeignKey(Order, related_name="items")
    product = models.ForeignKey(Product, related_name="order_items")
    quantity = models.PositiveIntegerField(default=1)

    ...

    def get_cost(self):
        return self.product.price * self.quantity

这是我的查询:
>>> Order.objects.all().aggregate(Sum("order_total"))

这会返回以下错误:

django.core.exceptions.FieldError: Cannot resolve keyword 'order_total' into field. Choices are: placed, customer, customer_id, id, items, paid

3
请看这个答案:https://dev59.com/V3A75IYBdhLWcg3w3NBe#3066607 尝试使用这个链接代替:https://docs.djangoproject.com/en/1.10/topics/db/aggregation/#aggregating-annotations - neverwalkaloner
1个回答

9

您需要使用双下划线__OrderItem模型中通过order作为查找字段查找订单总额的外键:

odrerObj = OrderItem.objects.all().aggregate(sum_order = Sum("order__order_total"))

但是如果您需要计算订单对象的order_total属性之和,可以使用以下方法:

order_list = Order.objects.all()
total = 0
for item in order_list :
    total += item.order_total()

print total

1
谢谢,我最终采用了你的第二个解决方案。 - Edward Chapman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接