Merge pull request #1032 from yprez/writable-nested-modelserializer_fixes

Writable nested serializer - fix setting nested serializer to null
This commit is contained in:
Tom Christie 2013-08-15 13:13:40 -07:00
commit 315435d00a
2 changed files with 25 additions and 4 deletions

View File

@ -522,7 +522,7 @@ class BaseSerializer(WritableField):
if self.object._deleted:
[self.delete_object(item) for item in self.object._deleted]
else:
self.save_object(self.object, **kwargs)
self.save_object(self.object, **kwargs)
return self.object
@ -891,7 +891,8 @@ class ModelSerializer(Serializer):
# Nested relationships need to be saved before we can save the
# parent instance.
for field_name, sub_object in obj._nested_forward_relations.items():
self.save_object(sub_object)
if sub_object:
self.save_object(sub_object)
setattr(obj, field_name, sub_object)
obj.save(**kwargs)

View File

@ -10,7 +10,8 @@ class OneToOneTarget(models.Model):
class OneToOneSource(models.Model):
name = models.CharField(max_length=100)
target = models.OneToOneField(OneToOneTarget, related_name='source')
target = models.OneToOneField(OneToOneTarget, related_name='source',
null=True, blank=True)
class OneToManyTarget(models.Model):
@ -21,7 +22,7 @@ class OneToManySource(models.Model):
name = models.CharField(max_length=100)
target = models.ForeignKey(OneToManyTarget, related_name='sources')
class ReverseNestedOneToOneTests(TestCase):
def setUp(self):
class OneToOneSourceSerializer(serializers.ModelSerializer):
@ -179,6 +180,25 @@ class ForwardNestedOneToOneTests(TestCase):
]
self.assertEqual(serializer.data, expected)
def test_one_to_one_update_to_null(self):
data = {'id': 3, 'name': 'source-3-updated', 'target': None}
instance = OneToOneSource.objects.get(pk=3)
serializer = self.Serializer(instance, data=data)
self.assertTrue(serializer.is_valid())
obj = serializer.save()
self.assertEqual(serializer.data, data)
self.assertEqual(obj.name, 'source-3-updated')
self.assertEqual(obj.target, None)
queryset = OneToOneSource.objects.all()
serializer = self.Serializer(queryset, many=True)
expected = [
{'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}},
{'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}},
{'id': 3, 'name': 'source-3-updated', 'target': None}
]
self.assertEqual(serializer.data, expected)
# TODO: Nullable 1-1 tests
# def test_one_to_one_delete(self):