【问题标题】:Obtain in the same query the number of active and inactive users in django在同一查询中获取 django 中的活跃和非活跃用户数
【发布时间】:2021-11-02 23:48:22
【问题描述】:

我有两个模型

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")),
    )

它不起作用。我该怎么做?

【问题讨论】:

标签: django orm


【解决方案1】:

您可以使用.aggregate(…) [Django-doc],我们使用Count(…) expression [Django-doc]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))
)

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多