[Answered ]-Obtain in the same query the number of active and inactive users in django

1👍

✅

You can work with an .aggregate(…) [Django-doc] where we use a Count(…) expression [Django-doc] with a filter=… parameter [Django-doc]:

from django.db.models import Count, Q

Agent.objects.aggregate(
    actifs=Count('user', filter=Q(user__is_active=True)),
    inactifs=Count('user', filter=Q(user__is_active=False))
)

This will return a dictionary with two entries: actifs and inactifs, for example:

{ 'actifs': 25, 'inactifs': 14 }

Leave a comment