class UpdateMobileSerializer(serializers.ModelSerializer):old = serializers.CharField(write_only=True, validators=[RegexValidator(r"\d{11}", message="格式错误")])mobile = serializers.CharField(write_only=True, validators=[RegexValidator(r"\d{11}", message="格式错误")])new_mobile = serializers.SerializerMethodField(read_only=True)class Meta:model = models.Companyfields = ['old', "mobile", "new_mobile"]def validate_old(self, val):# 当前登录用的手机号是不是request = self.context['request']user_id = request.user['id']exists = models.Company.objects.filter(id=user_id, mobile=val).exists()if not exists:raise ValidationError("原手机号错误")return valdef validate_mobile(self, val):# 新手机号,已存在exists = models.Company.objects.filter(mobile=val).exists()if exists:raise ValidationError("该手机已注册")return valdef get_new_mobile(self, obj):return obj.mobile[0:3] + "****" + obj.mobile[-4:]