From 03a56d9f10d34a5579d605fd4fe01d241772f572 Mon Sep 17 00:00:00 2001 From: xianfuxing Date: Sat, 11 Aug 2018 10:43:16 +0800 Subject: [PATCH] =?UTF-8?q?#=20=E4=BC=98=E5=8C=96=E7=BB=9F=E8=AE=A1?= =?UTF-8?q?=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/counter/api/views.py | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/apps/counter/api/views.py b/apps/counter/api/views.py index afadc54..5999cc3 100644 --- a/apps/counter/api/views.py +++ b/apps/counter/api/views.py @@ -44,14 +44,22 @@ class DeviceLogStatisticAPIView(APIView): tz = pytz.timezone("UTC") today = datetime.now(tz).date() midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None) - # total_count = DeviceCount.objects.aggregate(total=Sum('count'))['total'] - total_count_queryset = DeviceCount.objects.values('device_id').annotate(count=Max('count')) - total_count = sum(map(lambda x: int(x['count']), total_count_queryset)) + # calc total count + total_count_queryset = DeviceCount.objects.values('device_id').annotate(count=Max('count')) + if total_count_queryset: + total_count = sum(map(lambda x: int(x['count']), total_count_queryset)) + else: + total_count = 0 + + # calc daily count one_day_ago_queryset = DeviceCount.objects.filter( data_time__gt=midnight).values('device_id').annotate(count=Max('count')) - one_day_ago_count = sum(map(lambda x: int(x['count']), one_day_ago_queryset)) - daily_count = total_count - one_day_ago_count + if one_day_ago_queryset: + one_day_ago_count = sum(map(lambda x: int(x['count']), one_day_ago_queryset)) + daily_count = total_count - one_day_ago_count + else: + daily_count = 0 data = {'total_count': total_count, 'daily_count': daily_count} return Response(data)