我在 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/