# 优化统计判断

This commit is contained in:
xianfuxing 2018-08-11 10:43:16 +08:00
parent 69364bd979
commit 03a56d9f10
1 changed files with 13 additions and 5 deletions

View File

@ -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'))
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)