[Answered ]-Find Sum of Columns of Data in Django Like and Excel File

2👍

Django aggregation support this.

For aggregates grouped by a field, use a values clause with annotate , for example:

>>> from django.db.models import Count, Sum

>>> stats = Email.objects.all().values('month').annotate(
        Count('month'), Sum('recipients'), Sum('unsubscribes'), ...)
>>> stats
[{'month': 'January', 'month__count': 100, 'recipients__sum': 24, ... }
 {'month': 'February', 'month__count': 75, 'recipients__sum': 22, ... }]

You can also get totals from the database using aggregate:

>>> Email.objects.all().aggregate(
        Count(), Sum('recipients'), Sum('unsubscribes'), ...)

{'id__count': 175, 'recipients__sum': 46, ...}

However, it may be faster to avoid querying the database again, and calculate totals from what is already in memory (in by-month aggregations):

>>> totals = {}
>>> for key in ['month__count', 'recipients__sum', 'unsubscribes__sum', ...]:
...     totals[key] = sum(month.get(key, 0) for month in stats)

Leave a comment