Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 950
Edward Chapman Avatar asked Feb 07 '17 12:02

Edward Chapman


People also ask

What is @property in Django model?

What is @property in Django? Here is how I understand it: @property is a decorator for methods in a class that gets the value in the method. But, as I understand it, I can just call the method like normal and it will get it.

How do I add a model field in Django?

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB.

How is Django DB models model?

The basics: Each model is a Python class that subclasses django.db.models.Model . Each attribute of the model represents a database field. With all of this, Django gives you an automatically-generated database-access API; see Making queries.

How to get get count/average/min/max values from model field in Django?

Get count, average, min, max values from model field using Django Aggregate. Django queries help to create, retrieve, update and delete objects. But sometimes we need to get summered values from the objects. Then a Simple solution is to use Django aggregate feature Here are simple examples of how to use aggregation. app/models.py.

How many examples of Django models sum are there?

The following are 30 code examples of django.db.models.Sum () . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

How do I create a view by name in Django?

(You can’t define it in Django, it has to be created on the database, but you can use it by defining an unmanaged model that refers to the view by name.) I’d guess that it’s going to be at least as fast as an annotation added to a queryset.

How to get summered values from an object in Django?

But sometimes we need to get summered values from the objects. Then a Simple solution is to use Django aggregate feature Here are simple examples of how to use aggregation. To know the children count of a foreign key field.


1 Answers

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
like image 159
Prakhar Trivedi Avatar answered Oct 13 '22 11:10

Prakhar Trivedi