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

编程入门 行业动态 更新时间:2024-10-24 09:24:15
本文介绍了没有关系时计数并返回零的注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出以下关系:

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(零)。

I want to count how many requests have been created for each license type. However, since I am generating a graphic, I must include 0 (zero) for license types without any license request in that specific period.

我尝试执行建议的操作此处,但此操作无效。我只能从具有多个许可证请求的许可证类型中获得计数。

I tried to do what was suggested here, but it did not work. I can only get the count from License Types which have more than one license request.

qs = LicenseType.objects.filter( Q(licenserequest__created_at__range=(start_date, end_date)) | Q(licenserequest__isnull=True) ).annotate(rel_count=Count('licenserequest__id'))

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

I could find another way to achieve this goal, but I was wondering if I can do it through annotation.

我正在使用django1.11.15 。

推荐答案

在 djang-2.0 及更高版本, Count 对象的 filter 参数,因此我们可以为此指定代码:

In djang-2.0 and higher, the Count object has a filter parameter, so we can specify the codntions for this:

qs = LicenseType.objects.annotate( rel_count=Count( 'licenserequest', filter=Q(licenserequest__created_at__range=(start_date, end_date)) ) )

对于 djang-1.11 及以下版本,我们可以使用案例(的 Sum(..) ..)表达式:

For djang-1.11 and below, we can use the Sum(..) of a Case(..) expression:

qs = LicenseType.objects.annotate( rel_count=Sum(Case( When( licenserequest__created_at__range=(start_date, end_date), then=1 ), default=0, output_field=IntegerField() )) )

更多推荐

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

本文发布于:2023-10-28 18:31:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1537433.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时计   注释   关系

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!