【问题标题】:Calculate the sum of model properties in Django在Django中计算模型属性的总和
【发布时间】:2017-06-24 16:02:09
【问题描述】:

我有一个模型Order,它有一个属性,可以根据外键链接的OrderItems 计算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

【问题讨论】:

标签: python django django-models models


【解决方案1】:

您需要使用双下划线 __OrderItem 模型中以 order 作为查找字段的 order_total 的外键查找:

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

但是如果你需要 Order oject 的 order_total 属性的总和,你可以使用这样的东西:

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

print total

【讨论】:

  • 谢谢,我最终使用了您的第二个解决方案。
猜你喜欢
  • 2016-03-30
  • 2018-10-15
  • 2020-03-10
  • 2021-01-30
  • 1970-01-01
  • 2020-10-13
  • 2017-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多