在同一个查询中获取django中活跃用户和非活跃用户的数量

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

我有两个模型

class User(AbstractUser):
    ...

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

我想在单个请求中获得活跃用户和非活跃用户的数量。
我的要求:

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

没用。我该怎么做?

您可以使用 .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', <strong>filter=Q(user__is_active=True)</strong>),
    inactifs=Count('user', <strong>filter=Q(user__is_active=False)</strong>)
)

这将 return 一个包含两个条目的字典:actifsinactifs,例如:

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