7

I have a model Order which has a property that calculates an order_total based on OrderItems 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
Edward Chapman
  • 509
  • 6
  • 8
  • 3
    Look this answer: http://stackoverflow.com/a/3066607/641249 Try with this instead: https://docs.djangoproject.com/en/1.10/topics/db/aggregation/#aggregating-annotations – neverwalkaloner Feb 07 '17 at 12:27

1 Answers1

9

You need to use double underscore __ for foreign key lookup of order_total from OrderItem model with order as the lookup field:

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

But if you need sum of Order oject's order_total property, you can use something like this :

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

print total
Richard de Wit
  • 7,102
  • 7
  • 44
  • 54
Prakhar Trivedi
  • 8,218
  • 3
  • 28
  • 35