# 完善电量逻辑
This commit is contained in:
parent
420607619a
commit
263c336c04
|
@ -1,4 +1,4 @@
|
|||
from django.db.models import Q
|
||||
from django.db.models import Q, Min, Max
|
||||
from django.core.cache import cache
|
||||
from rest_framework import serializers
|
||||
from counter.models import DeviceCount, DeviceInfo
|
||||
|
@ -6,6 +6,22 @@ from mosquito.models import DeviceInfo as CelexDeviceInfo
|
|||
from mosquito.models import MosqPostStatistic, DevicePostStatistic
|
||||
|
||||
|
||||
def get_vol(device_id, cur_vol):
|
||||
vol_min_key = '{}_vol_min'.format(device_id)
|
||||
vol_max_key = '{}_vol_max'.format(device_id)
|
||||
vol_min = cache.get(vol_min_key)
|
||||
vol_max = cache.get(vol_max_key)
|
||||
if not vol_min:
|
||||
vol_min = DeviceCount.objects.filter(device_id=device_id).aggregate(vol_min=Min('vol'))['vol_min']
|
||||
cache.set(vol_min_key, vol_min, 60 * 5)
|
||||
if not vol_max:
|
||||
vol_max = DeviceCount.objects.filter(device_id=device_id).aggregate(vol_max=Max('vol'))['vol_max']
|
||||
cache.set(vol_max_key, vol_max, 60 * 5)
|
||||
|
||||
vol = 100 * (int(cur_vol) - int(vol_min)) / (int(vol_max) - int(vol_min))
|
||||
return '{}{}'.format(round(vol, 1), '%')
|
||||
|
||||
|
||||
class DeviceCountSerializer(serializers.ModelSerializer):
|
||||
device_name = serializers.SerializerMethodField()
|
||||
mosq_count = serializers.SerializerMethodField()
|
||||
|
@ -34,16 +50,16 @@ class DeviceCountSerializer(serializers.ModelSerializer):
|
|||
return obj.csq
|
||||
|
||||
def get_energy(self, obj):
|
||||
return obj.vol
|
||||
return get_vol(obj.device_id, obj.vol)
|
||||
|
||||
def get_calc_time(self, obj):
|
||||
return obj.data_time.strftime('%Y-%m-%d %H:%M:%S')
|
||||
|
||||
def get_device_name(self, obj):
|
||||
device_id = obj.device_id
|
||||
cache_content = cache.get(device_id)
|
||||
if cache_content:
|
||||
return cache_content
|
||||
device_name = cache.get(device_id)
|
||||
if device_name:
|
||||
return device_name
|
||||
qs = CelexDeviceInfo.objects.filter(device_id=device_id)
|
||||
if qs.count() > 0:
|
||||
device = qs[0]
|
||||
|
@ -105,7 +121,7 @@ class DeviceInfoSerializer(serializers.ModelSerializer):
|
|||
|
||||
def get_energy(self, obj):
|
||||
if self.latest:
|
||||
return self.latest.vol
|
||||
return get_vol(obj.device_id, self.latest.vol)
|
||||
return 0
|
||||
|
||||
def get_coordinate(self, obj):
|
||||
|
|
Loading…
Reference in New Issue