【问题标题】:Multiple Annotations Based on Different Filters In DjangoDjango中基于不同过滤器的多个注释
【发布时间】:2014-09-23 16:05:50
【问题描述】:

假设我有如下模型:

class Company(models.Model):
    name = models.CharField(max_length=255)

class Unit(models.Model):
    name = models.CharField(max_length=255)
    status = models.CharField(max_length=255)
    company = models.ForeignKey(Company)

我想在单个查询中获取所有公司的列表,并计算他们有多少单位“离线”以及有多少单位“在线”。

我知道如何通过以下方式获取其中之一的列表:

offline = Company.objects.all().filter(unit__status="offline").annotate(offline_count=Count("unit"))
online = Company.objects.all().filter(unit__status="online").annotate(online_count=Count("unit"))

我希望能够访问生成的查询集对象,例如:

companies[0].offline_count
companies[0].online_count

这可能吗?

【问题讨论】:

标签: django filter annotations django-queryset


【解决方案1】:

注意:django-aggregate-if 被 Django 1.8 中的相同功能所取代

【讨论】:

    【解决方案2】:

    这是你需要的:

    https://pypi.python.org/pypi/django-aggregate-if/

    from django.db.models import Q
    from aggregate_if import Count, Sum
    
    Company.objects.annotate(
        online_count=Count('unit', only=Q(unit__status="online")),
        offline_count=Count('unit', only=Q(unit__status="offline")),
    )
    

    【讨论】:

    • 这正是我所需要的!谢谢
    猜你喜欢
    • 2015-04-07
    • 2012-03-07
    • 2012-04-05
    • 2018-06-01
    • 2020-12-29
    • 2013-11-05
    • 2021-01-12
    • 1970-01-01
    • 2021-12-20
    相关资源
    最近更新 更多