我有一个模型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