根据Django中datetime字段中的“ HOUR”汇总小时计数

时间:2019-05-25 06:12:19

标签: python django django-orm

我正在使用Django 2.2和MySQL。我有以下查询: 这是供参考的模型:

class TrackCount(models.Model):
    people_count_obj_id = models.CharField(primary_key=True, default=uuid.uuid4,
                                           editable=False, max_length=255)
    recorded_at = models.DateTimeField()
    camera = models.ForeignKey(Camera, on_delete=models.PROTECT)
    store = models.ForeignKey(Store, on_delete=models.PROTECT)
    people_count_in = models.IntegerField()
    people_count_out = models.IntegerField()
    created_at = models.DateTimeField(auto_now=True)
    is_unique = models.BooleanField(default=False)

    def __str__(self):
        return "{}.{}.{}".format(self.people_count_in,
                                 self.people_count_out, str(self.store))

    class Meta:
        verbose_name = 'Track Count'
        verbose_name_plural = 'Track Counts'

================================================ ========= 我的查询是这样的。

track_events = TrackCount.objects.filter(
            recorded_at__date=start_date.date(),
            recorded_at__hour__range=(8, 23),
            store__store_owner__id=self.kwargs['account_id']).order_by(
            'recorded_at'
        ).extra(
            select={
                'hour': 'hour(recorded_at)'
            }
        ).values(
            'hour'
        ).annotate(
            TotalPeople=Sum('people_count_in')
        )

但是当我检查记录时,得到的输出如下:

[
    {
        "hour": 17,
        "TotalPeople": 22
    },
    {
        "hour": 17,
        "TotalPeople": 19
    },
    {
        "hour": 17,
        "TotalPeople": 30
    },
    {
        "hour": 18,
        "TotalPeople": 33
    },
    {
        "hour": 18,
        "TotalPeople": 31
    },
    {
        "hour": 18,
        "TotalPeople": 32
    },
    {
        "hour": 19,
        "TotalPeople": 32
    },
    {
        "hour": 19,
        "TotalPeople": 21
}] 

但是我想要这样的输出:

[{ "hour": 18, "TotalPeople": 96}....]是同一小时的记录,应该一起求和。

希望我的观点很清楚。 TIA

1 个答案:

答案 0 :(得分:0)

好的,所以实际上我花了几个小时才对它进行解码。由于我想要一个hour相同值的SUM-meded答案,因此最终查询是这样的。

track_events = TrackCount.objects.filter(
            recorded_at__date=start_date.date(),
            recorded_at__hour__range=(8, 23),
            store__store_owner__id=self.kwargs['account_id']).order_by(
            'recorded_at'
        ).extra(
            select={
                'hour': 'hour(recorded_at)'
            }
        ).values(
            'hour'
        ).annotate(
            TotalPeople=Sum('people_count_in')
        ).order_by('hour')