orm 多对多

参考链接

models

class alarmContact(models.Model):
    '''
    告警用户
    '''
    name = models.CharField('联系人名字', max_length=20, help_text='联系人名字', unique=True)
    phone = models.CharField('手机号码', max_length=11, null=False, help_text='手机号码')
    email = models.EmailField('邮箱', null=False)
    describe = models.CharField('字段描述', max_length=100, null=True, help_text='字段描述')

    def __str__(self):
        return self.name

    class Meta:
        db_table = 'monitoring_alarmContact'
        ordering = ['id']

class alarmContactGroup(models.Model):
    '''
    告警用户组
    '''
    alarmModeSelect = (
        ('U', 'only_userAlarm'),
        ('G', 'only_groupAlarm'),
        ('UG', 'user_groupAlarm')
    )
    id = models.AutoField(primary_key=True)
    groupname = models.CharField('报警联系组', max_length=20, help_text='报警联系组')
    member = models.ManyToManyField(alarmContact)
    dingding = models.CharField('dingding token', max_length=150, null=True, help_text='dingding token')
    alarmMode = models.CharField(max_length=2, choices=alarmModeSelect, default='U')
    describe = models.CharField('字段描述', max_length=100, null=True, help_text='字段描述')

    def __str__(self):
        return self.groupname

    class Meta:
        db_table = 'monitoring_alarmContactGroup'
        ordering = ['id']

serilaizers, 展示和增加分开

class alarmContactSerializer(serializers.ModelSerializer):
    describe = serializers.CharField(allow_null=True, allow_blank=True)

    class Meta:
        model = alarmContact
        fields = "__all__"

class addalarmContactGroupSerializer(serializers.Serializer):
    '''
    告警组新增
    '''
    groupname = serializers.CharField()
    member = serializers.CharField()
    dingding = serializers.CharField()
    alarmMode = serializers.CharField()
    describe = serializers.CharField(allow_blank=True,allow_null=True)

    def validate(self, attrs):
        try:
            alarmContactGroup.objects.filter(groupname__exact=attrs['groupname'])
            raise Exception('alarmContactGroupHasExist')
        except Exception as e:
            pass

        return attrs

    def create(self, validated_data):
        member = validated_data.pop('member')
        member_list = member.split(',')
        alarmContactGroup_obj = alarmContactGroup.objects.create(**validated_data)

        alarm_obj_list = []
        for alarmName in member_list:
            try:
                alarm_obj = alarmContact.objects.filter(name__exact=alarmName).values()[0]['id']
                alarm_obj_list.append(alarm_obj)
            except Exception as e:
                print("木有找到")

        alarmContactGroup_obj.member.add(*ll)
        alarmContactGroup_obj.save()

        return alarmContactGroup_obj

class alarmContactGroupSerializer(serializers.ModelSerializer):
    '''
    告警组展示
    '''
    alarmMode = serializers.CharField(source='get_alarmMode_display')

    class Meta:
        model = alarmContactGroup
        fields = "__all__"

    def to_representation(self, instance):
        res = super(alarmContactGroupSerializer, self).to_representation(instance)
        if bool(res['member']):
            res['member'] = [ alarmContact.objects.get(id=mem).name for mem in res['member'] ]
        return res

 

posted @ 2021-11-30 22:54  JvvYou  阅读(33)  评论(0编辑  收藏  举报