Fixed #24859 -- Made QuerySet.get() with UUIDField raise TypeError on bad value.

For consistency with AutoField.
This commit is contained in:
Cole Maclean 2015-06-04 14:42:26 +01:00 committed by Tim Graham
parent eaf4d8c0d8
commit 20ff296cb1
2 changed files with 18 additions and 7 deletions

View File

@ -2380,13 +2380,17 @@ class UUIDField(Field):
return "UUIDField" return "UUIDField"
def get_db_prep_value(self, value, connection, prepared=False): def get_db_prep_value(self, value, connection, prepared=False):
if isinstance(value, six.string_types): if value is None:
value = uuid.UUID(value) return None
if isinstance(value, uuid.UUID): if not isinstance(value, uuid.UUID):
if connection.features.has_native_uuid_field: try:
return value value = uuid.UUID(value)
return value.hex except AttributeError:
return value raise TypeError(self.error_messages['invalid'] % {'value': value})
if connection.features.has_native_uuid_field:
return value
return value.hex
def to_python(self, value): def to_python(self, value):
if value and not isinstance(value, uuid.UUID): if value and not isinstance(value, uuid.UUID):

View File

@ -37,6 +37,13 @@ class TestSaveLoad(TestCase):
loaded = NullableUUIDModel.objects.get() loaded = NullableUUIDModel.objects.get()
self.assertEqual(loaded.field, None) self.assertEqual(loaded.field, None)
def test_pk_validated(self):
with self.assertRaisesMessage(TypeError, 'is not a valid UUID'):
PrimaryKeyUUIDModel.objects.get(pk={})
with self.assertRaisesMessage(TypeError, 'is not a valid UUID'):
PrimaryKeyUUIDModel.objects.get(pk=[])
def test_wrong_value(self): def test_wrong_value(self):
self.assertRaisesMessage( self.assertRaisesMessage(
ValueError, 'badly formed hexadecimal UUID string', ValueError, 'badly formed hexadecimal UUID string',