【问题标题】:Django TruncHour + annotate Count not inlcuding hours with zero rowsDjango Trunc Hour + annotate Count 不包括零行的小时数
【发布时间】:2021-11-14 01:36:55
【问题描述】:

我有一个模特EventData

class EventData(models.Model):
    id = models.BigAutoField(primary_key=True)
    created = models.DateTimeField()
    session = models.ForeignKey(EventSession, on_delete=models.CASCADE)
    name = models.ForeignKey(EventName, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    value = models.CharField(max_length=200)

还有一个查询

event_volume = IngestModels.EventData.objects.filter(product=my_product, created__date=selected_date)
  .annotate(hour=TruncHour('created'))
  .annotate(event_count=Count('*'))
  .values("hour", "event_count")

产生类似的结果

hour event_count
2021-11-12 00:00:00 2
2021-11-12 01:00:00 2
2021-11-12 02:00:00 7
2021-11-12 05:00:00 5
2021-11-12 06:00:00 9
2021-11-12 09:00:00 10
2021-11-12 10:00:00 1
2021-11-12 12:00:00 9

您会注意到有时没有发生任何事件,因此行中省略了小时。如果没有发生任何事件,我真的希望每个小时都在场,0event_count 列中。所以像:

hour event_count
2021-11-12 00:00:00 2
2021-11-12 01:00:00 2
2021-11-12 02:00:00 7
2021-11-12 03:00:00 0
2021-11-12 04:00:00 0
2021-11-12 05:00:00 5
2021-11-12 06:00:00 9
2021-11-12 07:00:00 0
2021-11-12 08:00:00 0
2021-11-12 09:00:00 10
2021-11-12 10:00:00 1
2021-11-12 11:00:00 0
2021-11-12 12:00:00 9

任何帮助将不胜感激!我使用 PostgreSQL 作为我的数据库。

【问题讨论】:

    标签: python django postgresql


    【解决方案1】:

    我无法通过 ORM 解决这个问题,但在常规 Python 代码中填充数据很简单。

    def time_series_pad_zeros(time_series):
        result = []
        for i in range(0,24):
            found = False
            for data in time_series:
                if data['hour'].hour == i:
                    found = True
                    result.append({ "hour": i, "event_count": data['event_count'] })
    
            if not found:
                result.append({ "hour": i, "event_count": 0 })
    
        return result
    

    【讨论】:

      猜你喜欢
      • 2021-11-28
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      • 2011-02-21
      • 1970-01-01
      • 1970-01-01
      • 2013-04-22
      • 1970-01-01
      相关资源
      最近更新 更多