基于Django Token模型按小时统计当日至当前的记录数
当日每小时Token创建数量统计方案
需求说明
需要统计当日午夜到当前时间内,每个小时区间(如00:00-01:00、01:00-02:00…)的Token创建记录数量,要求统计逻辑在数据库端完成,避免在应用层加载当日所有Token记录后再循环统计。
Token模型定义
class Token(models.Model): customer_name = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) remarks = models.TextField(null=True,blank=True) modified_at = models.DateTimeField(auto_now=True)
解决方案
核心思路
- 生成当日从午夜到当前时间的所有小时区间,确保每个小时都有对应记录,哪怕该时段无Token创建
- 在数据库端对当日Token记录按小时截断分组,统计各时段的记录数
- 将生成的小时区间与统计结果做左关联,保证每个小时区间都能返回对应数量,无数据时显示0
Django ORM实现代码
from django.db.models import Count, Value from django.db.models.functions import TruncHour from django.utils import timezone from django.db import models # 获取当日午夜和当前时间 today_midnight = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0) now = timezone.now() # 生成当日需要统计的所有小时区间 hours = [] current_hour = today_midnight while current_hour <= now: hours.append(current_hour) current_hour += timezone.timedelta(hours=1) # 数据库端统计各小时的Token数量 token_hour_stats = Token.objects.filter( created_at__gte=today_midnight, created_at__lte=now ).annotate( hour_start=TruncHour('created_at') ).values('hour_start').annotate( count=Count('id') ).order_by('hour_start') # 合并区间与统计结果,补全无数据的小时 final_result = [] stat_index = 0 total_stats = len(token_hour_stats) for hour in hours: # 匹配对应小时的统计数据 if stat_index < total_stats and token_hour_stats[stat_index]['hour_start'] == hour: count = token_hour_stats[stat_index]['count'] stat_index += 1 else: count = 0 # 格式化区间显示文本(如01:00 AM对应00:00-01:00) interval_label = hour.strftime("%I:00 %p") final_result.append({ 'interval': interval_label, 'count': count }) # 输出结果(可根据需求调整展示格式) for item in final_result: print(f"{item['interval']:10} | {item['count']:5} |")
关键说明
- 使用
TruncHour函数在数据库端完成时间截断分组,所有统计逻辑由数据库执行 - 通过预生成小时区间并关联统计结果,解决了无数据小时不显示的问题
- 仅从数据库获取统计聚合后的结果,避免加载全量Token记录到应用层
预期结果格式
| Interval | count |
|---|---|
| 01:00 AM | 0 |
| 02:00 AM | 0 |
| ... | ... |
| 10:00 AM | 20 |
| 11:00 AM | 5 |
| ... | ... |
| 03:00 PM | 5 |
内容的提问来源于stack exchange,提问作者tjtharappel
相关产品推荐
相关产品推荐

