mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-01-24 00:04:16 +03:00
Raise appropriate error in serializer when making a partial update to set a required RelatedField to null (issue #1158)
This commit is contained in:
parent
e155534f4f
commit
cf6c11bd4b
|
@ -896,7 +896,10 @@ class ModelSerializer(Serializer):
|
||||||
# Update an existing instance...
|
# Update an existing instance...
|
||||||
if instance is not None:
|
if instance is not None:
|
||||||
for key, val in attrs.items():
|
for key, val in attrs.items():
|
||||||
|
try:
|
||||||
setattr(instance, key, val)
|
setattr(instance, key, val)
|
||||||
|
except ValueError:
|
||||||
|
self._errors[key] = self.error_messages['required']
|
||||||
|
|
||||||
# ...or create a new instance
|
# ...or create a new instance
|
||||||
else:
|
else:
|
||||||
|
|
|
@ -558,6 +558,29 @@ class ModelValidationTests(TestCase):
|
||||||
self.assertFalse(second_serializer.is_valid())
|
self.assertFalse(second_serializer.is_valid())
|
||||||
self.assertEqual(second_serializer.errors, {'title': ['Album with this Title already exists.']})
|
self.assertEqual(second_serializer.errors, {'title': ['Album with this Title already exists.']})
|
||||||
|
|
||||||
|
def test_foreign_key_is_null_with_partial(self):
|
||||||
|
"""
|
||||||
|
Test ModelSerializer validation with partial=True
|
||||||
|
|
||||||
|
Specifically test that a null foreign key does not pass validation
|
||||||
|
"""
|
||||||
|
album = Album(title='test')
|
||||||
|
album.save()
|
||||||
|
|
||||||
|
class PhotoSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = Photo
|
||||||
|
|
||||||
|
photo_serializer = PhotoSerializer(data={'description': 'test', 'album': album.pk})
|
||||||
|
self.assertTrue(photo_serializer.is_valid())
|
||||||
|
photo = photo_serializer.save()
|
||||||
|
|
||||||
|
# Updating only the album (foreign key)
|
||||||
|
photo_serializer = PhotoSerializer(instance=photo, data={'album': ''}, partial=True)
|
||||||
|
self.assertFalse(photo_serializer.is_valid())
|
||||||
|
self.assertTrue('album' in photo_serializer.errors)
|
||||||
|
self.assertEqual(photo_serializer.errors['album'], photo_serializer.error_messages['required'])
|
||||||
|
|
||||||
def test_foreign_key_with_partial(self):
|
def test_foreign_key_with_partial(self):
|
||||||
"""
|
"""
|
||||||
Test ModelSerializer validation with partial=True
|
Test ModelSerializer validation with partial=True
|
||||||
|
|
Loading…
Reference in New Issue
Block a user