310👍
You’re probably looking for aggregate
from django.db.models import Sum
ItemPrice.objects.aggregate(Sum('price'))
# returns {'price__sum': 1000} for example
64👍
Use .aggregate(Sum('column'))['column__sum']
reefer my example below
sum = Sale.objects.filter(type='Flour').aggregate(Sum('column'))['column__sum']
- [Django]-Get the list of checkbox post in django views
- [Django]-How to get the name of current app within a template?
- [Django]-Django Rest Framework – Updating a foreign key
53👍
Annotate adds a field to results:
>> Order.objects.annotate(total_price=Sum('price'))
<QuerySet [<Order: L-555>, <Order: L-222>]>
>> orders.first().total_price
Decimal('340.00')
Aggregate returns a dict with asked result:
>> Order.objects.aggregate(total_price=Sum('price'))
{'total_price': Decimal('1260.00')}
- [Django]-Format numbers in django templates
- [Django]-Can't compare naive and aware datetime.now() <= challenge.datetime_end
- [Django]-Django Rest Framework pagination extremely slow count
11👍
Using cProfile profiler, I find that in my development environment, it is more efficient (faster) to sum the values of a list than to aggregate using Sum()
.
eg:
sum_a = sum([item.column for item in queryset]) # Definitely takes more memory.
sum_b = queryset.aggregate(Sum('column')).get('column__sum') # Takes about 20% more time.
I tested this in different contexts and it seems like using aggregate
takes always longer to produce the same result. Although I suspect there might be advantages memory-wise to use it instead of summing a list.
- [Django]-How can I filter a Django query with a list of values?
- [Django]-Django: using more than one database with inspectdb?
- [Django]-Charts in django Web Applications
7👍
Previous answers are pretty well, also, you may get that total with a line of vanilla code…
items = ItemPrice.objects.all()
total_price = sum(items.values_list('price', flat=True))
- [Django]-Django create userprofile if does not exist
- [Django]-Best practices for adding .gitignore file for Python projects?
- [Django]-How to Unit test with different settings in Django?
4👍
You could also get the sum this way:
def total_sale(self):
total = Sale.objects.aggregate(TOTAL = Sum('amount'))['TOTAL']
return total
Replace the ‘amount’ with the column name from your model you want to calculate the sum of and replace ‘Sale’ with your model name.
- [Django]-What is a "slug" in Django?
- [Django]-Django – Annotate multiple fields from a Subquery
- [Django]-How to print BASE_DIR from settings.py from django app in terminal?
2👍
You need to use aggregate() and Sum() to calculate the sum of price
column as shown below. *The query with all() is equivalent to the query without all() as shown below:
from django.db.models import Sum
print(ItemPrice.objects.all().aggregate(Sum('price')))
print(ItemPrice.objects.aggregate(Sum('price')))
Then, these dictionaries below are outputted on console:
{'price__sum': Decimal('150.00')}
{'price__sum': Decimal('150.00')}
And, you can change the default key price__sum
to priceSum
for price column as shown below:
from django.db.models import Sum
# ↓ Here
print(ItemPrice.objects.all().aggregate(priceSum=Sum('price')))
print(ItemPrice.objects.aggregate(priceSum=Sum('price')))
# ↑ Here
Then, the default key is changed as shown below:
{'priceSum': Decimal('150.00')}
{'priceSum': Decimal('150.00')}
- [Django]-What does error mean? : "Forbidden (Referer checking failed – no Referer.):"
- [Django]-What is pip install -q -e . for in this Travis-CI build tutorial?
- [Django]-ValueError: The field admin.LogEntry.user was declared with a lazy reference