Categories
Python Answers

How to do count and group by with Python Django?

Spread the love

Sometimes, we want to do count and group by with Python Django.

In this article, we’ll look at how to do count and group by with Python Django.

How to do count and group by with Python Django?

To do count and group by with Python Django, we can use values to do group by and Count to add the count.

For instance, we write

from django.db.models import Count
theanswer = Item.objects.values('category').annotate(Count('category'))

to call values to do a group by with the category field.

And then we have Count('category') to count all the grouped items in all the groups.

Conclusion

To do count and group by with Python Django, we can use values to do group by and Count to add the count.

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 *