Aggregate hourly count based on “HOUR” in datetime field in Django

妖精的绣舞 提交于 2021-02-08 10:20:30

问题


I am using Django 2.2 along with MySQL. I have the following query: Here's the model for the reference :

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'

======================================================== My Query goes like this.

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')
        )

But when I check my records I get the output as following :

[
    {
        "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
}] 

But I would like the output something like this :

[{ "hour": 18, "TotalPeople": 96}....] that is the record for same hour should be SUM-ed up together.

Hope my point is clear. TIA


回答1:


Okay, so practically it took me couple of hour to decode this. Since I wanted a SUM-med up answer for same value of hour the final query was something like this.

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')


来源:https://stackoverflow.com/questions/56302262/aggregate-hourly-count-based-on-hour-in-datetime-field-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!