Calculate the sum of model properties in Django

2024/10/3 0:34:31

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
Answer

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
https://en.xdnf.cn/q/70790.html

Related Q&A

Set Host-header when using Python and urllib2

Im using my own resolver and would like to use urllib2 to just connect to the IP (no resolving in urllib2) and I would like set the HTTP Host-header myself. But urllib2 is just ignoring my Host-header:…

Full-featured date and time library

Im wondering if anyone knows of a good date and time library that has correctly-implemented features like the following:Microsecond resolution Daylight savings Example: it knows that 2:30am did not exi…

Mean of a correlation matrix - pandas data fram

I have a large correlation matrix in a pandas python DataFrame: df (342, 342).How do I take the mean, sd, etc. of all of the numbers in the upper triangle not including the 1s along the diagonal?Thank…

How to set imshow scale

Im fed up with matplotlib in that its so hard to plot images in specified size.Ive two images in 32*32, 20*20 sizes. I just want to plot them in its original size, or in proportion to its original size…

Python distutils gcc path

Im trying to cross-compile the pycrypto package, and Im getting closer and closer however, Ive hit an issue I just cant figure out.I want distutils to use the cross-compile specific gcc- so I set the C…

TypeError: builtin_function_or_method object has no attribute __getitem__

Ive got simple python functions.def readMainTemplate(templateFile):template = open(templateFile, r)data = template.read()index1 = data.index[[] #originally I passed it into data[]index2 = data.index[]]…

Extract currency amount from string in Python

Im making a program that takes currency from a string and converts it in to other currencies. For example, if the string was the car cost me $13,250 I would need to get $ and 13250. I have this regex a…

Error: The elasticsearch backend requires the installation of requests. How do I fix it?

Im having a issue when I ran "python manage.py rebuild_index" in my app supported by haystack and elasticsearch.Python 2.7 Django version 1.6.2 Haystack 2.1.0 Elasticsearch 1.0Please see the …

numpy: applying argsort to an array

The argsort() function returns a matrix of indices that can be used to index the original array so that the result would match the sort() result.Is there a way to apply those indices? I have two array…

Jinja2 for word templating

I would like to use jinja2 for word templating like mentioned is this short article. The problem Im facing is as follows, if I put {{title}} in my word-file the resulting xml can look like this:<w:r…