Merge pull request #1477 from vlastv/patch-1

Writable star source with instance
This commit is contained in:
Xavier Ordoquy 2014-03-31 07:49:23 +02:00
commit 73cd4e236f
2 changed files with 36 additions and 10 deletions

View File

@ -438,6 +438,15 @@ class BaseSerializer(WritableField):
raise ValidationError(self.error_messages['required']) raise ValidationError(self.error_messages['required'])
return return
if self.source == '*':
if value:
reverted_data = self.restore_fields(value, {})
if not self._errors:
into.update(reverted_data)
else:
if value in (None, ''):
into[(self.source or field_name)] = None
else:
# Set the serializer object if it exists # Set the serializer object if it exists
obj = get_component(self.parent.object, self.source or field_name) if self.parent.object else None obj = get_component(self.parent.object, self.source or field_name) if self.parent.object else None
@ -448,15 +457,6 @@ class BaseSerializer(WritableField):
is_simple_callable(getattr(obj, 'all', None))): is_simple_callable(getattr(obj, 'all', None))):
obj = obj.all() obj = obj.all()
if self.source == '*':
if value:
reverted_data = self.restore_fields(value, {})
if not self._errors:
into.update(reverted_data)
else:
if value in (None, ''):
into[(self.source or field_name)] = None
else:
kwargs = { kwargs = {
'instance': obj, 'instance': obj,
'data': value, 'data': value,

View File

@ -508,6 +508,32 @@ class ValidationTests(TestCase):
) )
self.assertEqual(serializer.is_valid(), True) self.assertEqual(serializer.is_valid(), True)
def test_writable_star_source_on_nested_serializer_with_parent_object(self):
class TitleSerializer(serializers.Serializer):
title = serializers.WritableField(source='title')
class AlbumSerializer(serializers.ModelSerializer):
nested = TitleSerializer(source='*')
class Meta:
model = Album
fields = ('nested',)
class PhotoSerializer(serializers.ModelSerializer):
album = AlbumSerializer(source='album')
class Meta:
model = Photo
fields = ('album', )
photo = Photo(album=Album())
data = {'album': {'nested': {'title': 'test'}}}
serializer = PhotoSerializer(photo, data=data)
self.assertEqual(serializer.is_valid(), True)
self.assertEqual(serializer.data, data)
def test_writable_star_source_with_inner_source_fields(self): def test_writable_star_source_with_inner_source_fields(self):
""" """
Tests that a serializer with source="*" correctly expands the Tests that a serializer with source="*" correctly expands the