简体   繁体   English

Django groupby day 用 0 填充缺失的数据

[英]Django groupby day fill missing data with 0

I want to make a request in Django where I group by day but I want to fill the day where there is no result with 0, is it possible?我想在 Django 中按天分组,但我想用 0 填充没有结果的那一天,这可能吗?

# I use the following query
AccessLog
 .objects
 .filter(attempt_time__gte=last_30_days)
 .annotate(day=TruncDay('attempt_time'))
 .values('day', 'username')
 .annotate(c = Count('username'))
 .order_by('day')

No, it is not possible with annotations.不,注释是不可能的。 Annotations work with the similar types, for example, Coalesce function requires similar types and mixing datetime and numbers will result in a database error.注释适用于相似的类型,例如, Coalesce函数需要相似的类型,混合日期时间和数字会导致数据库错误。 The same for the Case function there is only one output field per result.对于Case函数,每个结果只有一个输出字段。

The function TruncDay returns a DateTime (in this case) with fields up to Day set to their minimum value, so for instance 2015-06-15 14:30:50.000321+00:00 will be converted to 2015-01-01 00:00:00+00:00 how documentation outlines.函数TruncDay返回一个 DateTime(在本例中),其中 Day 的字段设置为最小值,因此例如2015-06-15 14:30:50.000321+00:00将转换为2015-01-01 00:00:00+00:00文档概述。 And actually annotated value cannot be sometimes integer and sometimes datetime object.实际上注释的值有时不能是整数,有时是日期时间对象。

Occasionally to denote that the values are "None" in such situations preferable way would be to set it to the minimal/maximum value (we assume that the value cannot be equal to it), for instance:偶尔表示在这种情况下值是“无”,最好的方法是将其设置为最小值/最大值(我们假设该值不能等于它),例如:

AccessLog.objects.filter(
        attempt_time__gte=last_30_days
    ).annotate(
        day=Coalesce(TruncDay('attempt_time'), datetime.min)
    ).values('day', 'username').annotate(
        c=Count('username')
    ).order_by('day')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM