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,16 +438,6 @@ class BaseSerializer(WritableField):
raise ValidationError(self.error_messages['required'])
return
# Set the serializer object if it exists
obj = get_component(self.parent.object, self.source or field_name) if self.parent.object else None
# If we have a model manager or similar object then we need
# to iterate through each instance.
if (self.many and
not hasattr(obj, '__iter__') and
is_simple_callable(getattr(obj, 'all', None))):
obj = obj.all()
if self.source == '*':
if value:
reverted_data = self.restore_fields(value, {})
@ -457,6 +447,16 @@ class BaseSerializer(WritableField):
if value in (None, ''):
into[(self.source or field_name)] = None
else:
# Set the serializer object if it exists
obj = get_component(self.parent.object, self.source or field_name) if self.parent.object else None
# If we have a model manager or similar object then we need
# to iterate through each instance.
if (self.many and
not hasattr(obj, '__iter__') and
is_simple_callable(getattr(obj, 'all', None))):
obj = obj.all()
kwargs = {
'instance': obj,
'data': value,

View File

@ -508,6 +508,32 @@ class ValidationTests(TestCase):
)
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):
"""
Tests that a serializer with source="*" correctly expands the