teapot teapot - 2 months ago 6
Python Question

What's this after aggregation in django?

I see the following code from a django project. I understand it's aggregation, but what's ['kw__sum'] after the aggregation?

Project.objects.filter(project = project).aggregate(Sum('kw'))['kw__sum']


Thanks

Answer

Here if you look in examples you will see that aggregate returns dictionary so last part is just dict lookup

aggregation = Project.objects.filter(project = project).aggregate(Sum('kw'))
result = aggregation['kw__sum']

From the docs

Returns a dictionary of aggregate values (averages, sums, etc.) calculated over the QuerySet. Each argument to aggregate() specifies a value that will be included in the dictionary that is returned.

Comments