0

我有包含“caller_name”和“call_datetime”字段的模型。

我能够获得特定月份每天发生的电话数量:

while start_date <= end_date:
    calls = CDR.objects.filter(start_time__year=str(start_date.year), start_time__month=str(start_date.month), 
                                    start_time__day=str(start_date.day))
    print "Number of calls:", len(calls)
    start_date = start_date + datetime.timedelta(days=1)

同样,我试图在特定日期每小时获得电话数量。

for i in range(24):
    calls = CDR.objects.filter(start_time__year=str(start_date.year), start_time__month=str(start_date.month),start_time__day=str(start_date.day), start_time__hour=str(i))

发现“start_time__hour”没有实现,但是以他们的任何方式来实现这一点?

4

2 回答 2

2

试试这个解决方法:

day_calls = CDR.objects.filter(start_time__year=str(start_date.year), start_time__month=str(start_date.month),start_time__day=str(start_date.day))

hour_calls = day_calls.extra(select={'hours': 'DATE_FORMAT(start_date, "%%H")'})\
                      .values_list('hours', flat=True)\
                      .distinct()\
                      .order_by('hours')
于 2012-12-08T11:51:11.683 回答
1

您可以使用带有该.extra()方法的原始 SQL 或类似的东西:

for i in range(24):
    dt1 = start_time.replace(hour=i)
    dt2 = dt1 + datetime.timedelta(hours=1)
    calls = CDR.objects.filter(start_time__gte=dt1, start_time__lt=dt2)
于 2012-12-08T11:49:44.203 回答