I have a model Order
which has a property that calculates an order_total
based on OrderItem
s linked by foreign key.
I would like to calculate the sum of a number of Order
instances' order_total
properties.
Is there a way of doing this?
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
This is my query:
>>> Order.objects.all().aggregate(Sum("order_total"))
Which returns this error:
django.core.exceptions.FieldError: Cannot resolve keyword 'order_total' into field. Choices are: placed, customer, customer_id, id, items, paid