# 改为本月数据

This commit is contained in:
xianfuxing 2020-05-27 17:59:39 +08:00
parent 4a781f45f8
commit 8663ae5022
1 changed files with 22 additions and 3 deletions

View File

@ -87,12 +87,30 @@ class DeviceLogStatisticAPIView(APIView, RoleMixin):
else: else:
total_count = 0 total_count = 0
tz = pytz.timezone("UTC")
today = datetime.now(tz).date()
# calc monthly count, put it in redis as cache.
if cache.has_key('monthly_count'):
monthly_count = cache.get('monthly_count')
else:
cur_month = tz.localize(datetime.combine(datetime(today.year, today.month, 1), time(0, 0)), is_dst=None)
one_month_ago_queryset = [
DeviceCount.objects.filter(device_id=x['device_id'], data_time=x['max_time']).order_by('-count')[0]
for x in DeviceCount.objects.filter(
data_time__lt=cur_month, device_id__in=devices).values('device_id').annotate(
max_time=Max('data_time'))]
if one_month_ago_queryset:
one_month_ago_count = sum(map(lambda x: int(x.count), one_month_ago_queryset))
monthly_count = total_count - one_month_ago_count
else:
monthly_count = 0
cache.set('monthly_count', monthly_count, 60 * 60)
# calc daily count, put it in redis as cache. # calc daily count, put it in redis as cache.
if cache.has_key('daily_count'): if cache.has_key('daily_count'):
daily_count = cache.get('daily_count') daily_count = cache.get('daily_count')
else: else:
tz = pytz.timezone("UTC")
today = datetime.now(tz).date()
midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None) midnight = tz.localize(datetime.combine(today, time(0, 0)), is_dst=None)
one_day_ago_queryset = [DeviceCount.objects.filter(device_id=x['device_id'], data_time=x['max_time']).order_by('-count')[0] one_day_ago_queryset = [DeviceCount.objects.filter(device_id=x['device_id'], data_time=x['max_time']).order_by('-count')[0]
for x in DeviceCount.objects.filter( for x in DeviceCount.objects.filter(
@ -103,7 +121,8 @@ class DeviceLogStatisticAPIView(APIView, RoleMixin):
else: else:
daily_count = 0 daily_count = 0
cache.set('daily_count', daily_count, 60 * 60) cache.set('daily_count', daily_count, 60 * 60)
data = {'total_count': total_count, 'daily_count': daily_count}
data = {'total_count': total_count - monthly_count, 'daily_count': daily_count}
return Response(data) return Response(data)
def get_devices(self): def get_devices(self):