from apps.utils.serializers import CustomModelSerializer from apps.enm.models import Mpoint, MpLog, MpointStat from apps.utils.constants import EXCLUDE_FIELDS from rest_framework import serializers from apps.mtm.models import Mgroup from rest_framework.exceptions import ParseError from django.utils.timezone import localtime class MpointSerializer(CustomModelSerializer): mgroup = serializers.PrimaryKeyRelatedField(label="测点集", queryset=Mgroup.objects.all(), required=True) mgroup_name = serializers.CharField(source='mgroup.name', read_only=True) belong_dept_name = serializers.CharField(source='belong_dept.name', read_only=True) ep_monitored_name = serializers.CharField(source='ep_monitored.name', read_only=True) ep_belong_name = serializers.CharField(source='ep_belong.name', read_only=True) material_name = serializers.CharField(source='material.name', read_only=True) class Meta: model = Mpoint fields = '__all__' read_only_fields = EXCLUDE_FIELDS + ['belong_dept', 'cate'] def validate(self, attrs): if 'material' in attrs and attrs['material']: attrs['cate'] = 'material' attrs['belong_dept'] = attrs['mgroup'].belong_dept return attrs class MpLogSerializer(CustomModelSerializer): mpoint_name = serializers.CharField(source='mpoint.name', read_only=True) class Meta: model = MpLog fields = '__all__' read_only_fields = EXCLUDE_FIELDS + ['mpoint_name'] class MpointStatSerializer(CustomModelSerializer): mpoint_name = serializers.CharField(source='mpoint.name', read_only=True) class Meta: model = MpointStat fields = '__all__' read_only_fields = EXCLUDE_FIELDS + ['mpoint_name', 'type', 'mpoint', 'year', 'month', 'day'] def check_required_keys(dictionary, keys): for key in keys: if key not in dictionary or not dictionary[key]: return False return True def validate(self, attrs): if 'sflog' in attrs and attrs['sflog']: attrs['type'] = 'sflog' sflog = attrs['sflog'] end_time_local = localtime(sflog.end_time) attrs['year_s'], attrs['month_s'], attrs['day_s'] = end_time_local.year, end_time_local.month, end_time_local.day else: keys = ['hour', 'day_s', 'month_s', 'year_s'] for ind, key in enumerate(keys): if key in attrs and attrs['key']: if not self.check_required_keys(attrs, keys[ind+1:]): raise ParseError('缺少数据') attrs['type'] = key return super().validate(attrs)