diff --git a/python-packages/securesync/devices/models.py b/python-packages/securesync/devices/models.py index 1d0cd002d6..b84efe9bfe 100755 --- a/python-packages/securesync/devices/models.py +++ b/python-packages/securesync/devices/models.py @@ -8,7 +8,7 @@ from django.conf import settings from django.contrib.auth.models import check_password from django.core.exceptions import ValidationError, ObjectDoesNotExist -from django.db import models, transaction +from django.db import models, transaction, IntegrityError from django.db.models import Q from django.db.models.expressions import F from django.utils.text import compress_string @@ -208,9 +208,13 @@ def set_key(self, key): def get_key(self): if not self.key: - if self.get_metadata().is_own_device: - self.key = crypto.get_own_key() - elif self.public_key: + try: + if self.get_metadata().is_own_device: + self.key = crypto.get_own_key() + except Device.DoesNotExist: + # get_metadata can fail if the Device instance hasn't been persisted to the db + pass + if not self.key and self.public_key: self.key = crypto.Key(public_key_string=self.public_key) return self.key @@ -219,7 +223,12 @@ def _hashable_representation(self): return super(Device, self)._hashable_representation(fields=fields) def get_metadata(self): - return DeviceMetadata.objects.get_or_create(device=self)[0] + try: + return DeviceMetadata.objects.get_or_create(device=self)[0] + except IntegrityError as e: + # Possible from get_or_create if the DeviceMetadata object doesn't exist + # and the Device hasn't been persisted to the database yet. + raise Device.DoesNotExist() def get_counter_position(self): """