从午夜到当前时间的每个小时间隔内创建的记录数

问题描述 投票:0回答:1

我需要检索从午夜到当前时间的每个小时内创建的记录数。为此,模型包含一个

created_at
时间戳字段,它将记录创建时间。 模型定义如下。

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)

在 SQL 输出中寻找如下结果

Intervel  | count|
-----------------|       
01:00 AM  |   0  |  # 00:00 to 01:00 AM 
02:00 AM  |   0  |
   .......
10:00 AM  |  20  |
11:00 AM  |   5  |
  ........
03:00 PM  |   5  |
------------------

我需要获取可以在数据库端执行上述操作的模型查询,而无需加载从午夜到现在一天中创建的所有记录,然后通过在应用程序中运行 forloop 来获取计数。请帮助我..

django django-models django-queryset django-4.1
1个回答
0
投票

为此,您需要使用

values
annotate


from django.db.models import Count 
from your_models import Token 
from django.utils import timezone

# Get records for today.
records_today = Token.objects.filter(created_at__date=timezone.now().date()) 

# Group the records by the hour, then annotate will work on that group. 
per_hour_count = record_today.values("created_at__hour").annotate(count=Count("pk")).order_by("created_at")

© www.soinside.com 2019 - 2024. All rights reserved.