django - 没有关系时计数并返回零的注释

标签 django django-queryset

鉴于以下关系:

class LicenseRequest:
    license_type = models.ForeignKey(LicenseType)
    created_at = models.DateField(default=now, editable=False)

class LicenseType:
    name = models.CharField(max_length=100)
    value = models.CharField(max_length=3, unique=True)

我想计算为每种许可证类型创建了多少个请求。但是,由于我正在生成图形,因此对于在该特定时期内没有任何许可证请求的许可证类型,我必须包含 0(零)。

我试着按照建议的做 here ,但它没有用。我只能从具有多个许可证请求的许可证类型中获取计数。
qs = LicenseType.objects.filter(
                Q(licenserequest__created_at__range=(start_date, end_date)) | Q(licenserequest__isnull=True)
            ).annotate(rel_count=Count('licenserequest__id'))

我可以找到另一种方法来实现这个目标,但我想知道是否可以通过注释来实现。

我正在使用 .

最佳答案

和更高,Count对象有一个 filter参数,因此我们可以为此指定条件:

qs = LicenseType.objects.annotate(
    rel_count=Count(
        'licenserequest',
        filter=Q(licenserequest__created_at__range=(start_date, end_date))
    )
)
对于 及以下,我们可以使用 Sum(..)Case(..)表达:
qs = LicenseType.objects.annotate(
    rel_count=Sum(Case(
        When(
            licenserequest__created_at__range=(start_date, end_date),
            then=1
        ),
        default=0,
        output_field=IntegerField()
    ))
)

关于django - 没有关系时计数并返回零的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52290430/

相关文章:

python - 在 Django 中,如何过滤或排除多项内容?

python - 如何在 Django 的 HTML 页面上显示 blob 图像?

mysql - 带有额外选择的 Django 查询集计数

django - 过滤然后遍历嵌套的Django模型

python - Django:{{ request.user }} 在模板中没有显示任何内容

django - 使用类似于 Rails JST 的 Django 管道分配 Backbone 模板?

jquery - 我自己的点赞按钮: Django + Ajax -- How?

Django 查询集 - 包括 ManyToMany 中整个集合的对象

python - django 中模型 FK 关系的查询集

python - Django:如何在django.db.models.query QuerySet中重载Q以用于我的Manager中的特殊用途