Sometimes, we want to group by and aggregate with Python Django.
In this article, we’ll look at how to group by and aggregate with Python Django.
How to group by and aggregate with Python Django?
To group by and aggregate with Python Django, we call values and an aggergate function.
For instance, we write
Rating.objects.filter(attribute__in=attributes)
.values('location')
.annotate(score = Sum('score'))
.order_by('-score')
to call values with 'location' to group by location.
And then we call annotate with score set to the result of calling Sum with 'score' to sum up the grouped items’ score values.
Conclusion
To group by and aggregate with Python Django, we call values and an aggergate function.