假设我有一个看起来像这样的模型:
class Action(models.Model):
timestamp = models.DateTimeField(default=timezone.now)
# ...
如何查看,
Action.objects
将它们分为24个方括号(使用QuerySet属性,可能是group
吗?),如下所示:
{ 0: [Action1, Action2, Action3], # timestamp between 00:00 and 00:59, any day
1: [Action4], # timestamp between 01:00 and 01:59, any day
# ...
23: [ActionN] # timestamp between 23:00 and 23:59, any day
}
基本上,我想有一个图表来显示完成了多少次操作,分辨率为一个小时。
答案 0 :(得分:1)
您可以利用ExtractHour函数从日期时间字段中获取小时,然后将记录分组为dict
。
示例代码供您参考:
from collections import defaultdict
from django.db.models.functions import ExtractHour
# create a new field to extract hour from timestamp field
actions = Action.objects.annotate(hour=ExtractHour('created'))
# create a default dict to insert a list if key is not exist
results = defaultdict(lambda: [])
for row in actions:
results[row.hour].append(row)
注意:
如果您使用的是mysql数据库,请记住在使用Extract
函数之前先加载时区信息
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql