python - Django聚合函数问题(Count = -number-)

标签 python django django-models

User
   id
   name
Device
   id
   name
   user-id
   is_enabled 

我想选择所有拥有
的用户

  1. 至少启用一台设备。
  2. 仅启用 2 台设备
  3. 所有设备均已启用

    注意:启用意味着(Device.is_enabled = 1)

我知道我可以使用注释来获取设备数量。但是如何使用 annonate 来获取恰好拥有 2 个启用设备的用户数量,

我现在正在搞事情

User.objects.filter('device_set__is_enabled'=1)

它提供至少拥有一台启用的设备的用户列表。 不知道下一步该做什么。

最佳答案

from django.db.models import Count
User.objects.filter(device__is_enabled=1).annotate(
    device_count=Count('device')).filter(device_count=2)

User.objects.exclude(device__is_enabled=0)

关于python - Django聚合函数问题(Count = -number-),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6955775/

相关文章:

python - 错误 :AttributeError: 'super' object has no attribute 'db_type' when run "python manage.py syncdb" in django

python - 在python中转换unicode字符串

python - [Python]拆分csv文件的元素并插入mysql

django - 公开之前如何预热Django Web服务?

python - django.apps : an error appears during the template rendering when I loop on get_models()

python - 如何使用 URL 正则表达式来匹配 Django 中帖子的确切日期?

python - 将 datetime.max 插入 pandas 系列会更改系列类型

python - 对数组进行排序并将索引追溯到其排序顺序

django 外键包含查询

django - 我应该如何在我的模型中使用 DurationField?