leauradmin
leauradmin

Reputation: 385

Obtain in the same query the number of active and inactive users in django

I have two models

class User(AbstractUser):
    ...

class Agent(models.Model):
    ...
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="agent")

I want to have the number of active and inactive users in a single request.
My request:

Agent.objects.annotate(
        actifs=Count(User.objects.values("id").filter("is_active")),
        inactifs=Count(User.objects.values("id").filter("is_active=False")),
    )

It does not work. How i can do it ?

Upvotes: 1

Views: 610

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477160

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 }

Upvotes: 1

Related Questions