Search code examples
pythondjangodjango-modelsmodels

Calculate the sum of model properties in Django


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

Solution

  • 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