python - Django 按小时分组

标签 python django orm group-by

我在 Django 中有以下模型。

class StoreVideoEventSummary(models.Model):
    Customer = models.ForeignKey(GlobalCustomerDirectory, null=True, db_column='CustomerID', blank=True, db_index=True)
    Store = models.ForeignKey(Store, null=True, db_column='StoreID', blank=True, related_name="VideoEventSummary")
    Timestamp = models.DateTimeField(null=True, blank=True, db_index=True)
    PeopleCount = models.IntegerField(null=True, blank=True)

我想知道每小时进入商店的人数。

为此,我尝试按 Timestamp 上的小时对行进行分组,并对 PeopleCount 列求和。

store_count_events = StoreVideoEventSummary.objects.filter(Timestamp__range=(start_time, end_time),
                                                       Customer__id=customer_id,
                                                       Store__StoreName=store)\
        .order_by("Timestamp")\
        .extra({
            "hour": "date_part(\'hour\', \"Timestamp\")"
        }).annotate(TotalPeople=Sum("PeopleCount"))

这似乎没有按小时对结果进行分组,它只是向查询中的每一行添加了一个新列 TotalPeople,它与 PeopleCount 具有相同的值放。

最佳答案

把它分成两步

import itertools
from datetime import datetime


# ...

def date_hour(timestamp):
    return datetime.fromtimestamp(timestamp).strftime("%x %H")


objs = StoreVideoEventSummary.objects.filter(
    Timestamp__range=(start_time, end_time),
    Customer__id=customer_id,
    Store__StoreName=store
).order_by("Timestamp")

groups = itertools.groupby(objs, lambda x: date_hour(x.Timestamp))

# since groups is an iterator and not a list you have not yet traversed the list
for group, matches in groups:  # now you are traversing the list ...
    print(group, "TTL:", sum(1 for _ in matches))

这允许您根据几个不同的标准进行分组

你只想要小时而不考虑日期只需更改date_hour

def date_hour(timestamp):
   return datetime.fromtimestamp(timestamp).strftime("%H")

如果您想按刚使用的星期几分组

def date_day_of_week(timestamp):
   return datetime.fromtimestamp(timestamp).strftime("%w %H")

并更新 itertools.groupby 的 lambda 以使用 date_day_of_week

关于python - Django 按小时分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30465013/

相关文章:

Django 如何部分渲染

database - 在 Doctrine 2 中指定 decimal 字段类型时,scale 和 precision 意味着什么?

python - Django ManyToManyField 中的 'through' 参数是否包含所有字段?

python - 子类化 Python 列表以验证新项目

python - pandas .sortlevel 无法对负数进行排序

python - 属性错误 : 'module' object has no attribute 'setdefaultencoding'

python - 初始化 QueryDict.fromkeys

c# - 使用索引器从数据存储中检索 Linq to SQL 对象

c# - Iridium ORM - 无法创建关系。 (

python - 在 python 函数中使用列表