Categories
Python Answers

How to group by and aggregate with Python Django?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *