guettli
guettli

Reputation: 27969

Django-ORM: Count number of groups of each user

I know that I can get the number of groups each user has with this query:

User.objects.filter(groups__in=Group.objects.all()).annotate(Count('pk'))

But something is missing:

The users which are in no group at all.

How can I use the django orm to get all users annotated by their group count, incluse users with no group?

Upvotes: 0

Views: 647

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47364

You can use Count method with groups attribute:

from django.db.models import Count
User.objects.annotate(group_count=Count('groups'))

Upvotes: 1

Related Questions