mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-01-24 00:04:16 +03:00
Merge pull request #556 from maspwr/one-to-one-nested
One-to-one writable, nested serializer support
This commit is contained in:
commit
ecb4494994
|
@ -93,7 +93,7 @@ class SerializerOptions(object):
|
||||||
self.exclude = getattr(meta, 'exclude', ())
|
self.exclude = getattr(meta, 'exclude', ())
|
||||||
|
|
||||||
|
|
||||||
class BaseSerializer(Field):
|
class BaseSerializer(WritableField):
|
||||||
class Meta(object):
|
class Meta(object):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
@ -118,6 +118,7 @@ class BaseSerializer(Field):
|
||||||
self._data = None
|
self._data = None
|
||||||
self._files = None
|
self._files = None
|
||||||
self._errors = None
|
self._errors = None
|
||||||
|
self._delete = False
|
||||||
|
|
||||||
#####
|
#####
|
||||||
# Methods to determine which fields to use when (de)serializing objects.
|
# Methods to determine which fields to use when (de)serializing objects.
|
||||||
|
@ -218,7 +219,10 @@ class BaseSerializer(Field):
|
||||||
try:
|
try:
|
||||||
field.field_from_native(data, files, field_name, reverted_data)
|
field.field_from_native(data, files, field_name, reverted_data)
|
||||||
except ValidationError as err:
|
except ValidationError as err:
|
||||||
self._errors[field_name] = list(err.messages)
|
if hasattr(err, 'message_dict'):
|
||||||
|
self._errors[field_name] = [err.message_dict]
|
||||||
|
else:
|
||||||
|
self._errors[field_name] = list(err.messages)
|
||||||
|
|
||||||
return reverted_data
|
return reverted_data
|
||||||
|
|
||||||
|
@ -369,6 +373,35 @@ class ModelSerializer(Serializer):
|
||||||
"""
|
"""
|
||||||
_options_class = ModelSerializerOptions
|
_options_class = ModelSerializerOptions
|
||||||
|
|
||||||
|
def field_from_native(self, data, files, field_name, into):
|
||||||
|
if self.read_only:
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
value = data[field_name]
|
||||||
|
except KeyError:
|
||||||
|
if self.required:
|
||||||
|
raise ValidationError(self.error_messages['required'])
|
||||||
|
return
|
||||||
|
|
||||||
|
if self.parent.object:
|
||||||
|
# Set the serializer object if it exists
|
||||||
|
pk_field_name = self.opts.model._meta.pk.name
|
||||||
|
obj = getattr(self.parent.object, field_name)
|
||||||
|
self.object = obj
|
||||||
|
|
||||||
|
if value in (None, ''):
|
||||||
|
self._delete = True
|
||||||
|
into[(self.source or field_name)] = self
|
||||||
|
else:
|
||||||
|
obj = self.from_native(value, files)
|
||||||
|
if not self._errors:
|
||||||
|
self.object = obj
|
||||||
|
into[self.source or field_name] = self
|
||||||
|
else:
|
||||||
|
# Propagate errors up to our parent
|
||||||
|
raise ValidationError(self._errors)
|
||||||
|
|
||||||
def get_default_fields(self):
|
def get_default_fields(self):
|
||||||
"""
|
"""
|
||||||
Return all the fields that should be serialized for the model.
|
Return all the fields that should be serialized for the model.
|
||||||
|
@ -542,10 +575,13 @@ class ModelSerializer(Serializer):
|
||||||
|
|
||||||
return instance
|
return instance
|
||||||
|
|
||||||
def save(self):
|
def _save(self, parent=None, fk_field=None):
|
||||||
"""
|
if self._delete:
|
||||||
Save the deserialized object and return it.
|
self.object.delete()
|
||||||
"""
|
return
|
||||||
|
|
||||||
|
if parent and fk_field:
|
||||||
|
setattr(self.object, fk_field, parent)
|
||||||
self.object.save()
|
self.object.save()
|
||||||
|
|
||||||
if getattr(self, 'm2m_data', None):
|
if getattr(self, 'm2m_data', None):
|
||||||
|
@ -555,9 +591,18 @@ class ModelSerializer(Serializer):
|
||||||
|
|
||||||
if getattr(self, 'related_data', None):
|
if getattr(self, 'related_data', None):
|
||||||
for accessor_name, object_list in self.related_data.items():
|
for accessor_name, object_list in self.related_data.items():
|
||||||
setattr(self.object, accessor_name, object_list)
|
if isinstance(object_list, ModelSerializer):
|
||||||
|
fk_field = self.object._meta.get_field_by_name(accessor_name)[0].field.name
|
||||||
|
object_list._save(parent=self.object, fk_field=fk_field)
|
||||||
|
else:
|
||||||
|
setattr(self.object, accessor_name, object_list)
|
||||||
self.related_data = {}
|
self.related_data = {}
|
||||||
|
|
||||||
|
def save(self):
|
||||||
|
"""
|
||||||
|
Save the deserialized object and return it.
|
||||||
|
"""
|
||||||
|
self._save()
|
||||||
return self.object
|
return self.object
|
||||||
|
|
||||||
|
|
||||||
|
|
124
rest_framework/tests/nesting.py
Normal file
124
rest_framework/tests/nesting.py
Normal file
|
@ -0,0 +1,124 @@
|
||||||
|
from django.db import models
|
||||||
|
from django.test import TestCase
|
||||||
|
from rest_framework import serializers
|
||||||
|
|
||||||
|
|
||||||
|
class OneToOneTarget(models.Model):
|
||||||
|
name = models.CharField(max_length=100)
|
||||||
|
|
||||||
|
|
||||||
|
class OneToOneTargetSource(models.Model):
|
||||||
|
name = models.CharField(max_length=100)
|
||||||
|
target = models.OneToOneField(OneToOneTarget, null=True, blank=True,
|
||||||
|
related_name='target_source')
|
||||||
|
|
||||||
|
|
||||||
|
class OneToOneSource(models.Model):
|
||||||
|
name = models.CharField(max_length=100)
|
||||||
|
target_source = models.OneToOneField(OneToOneTargetSource, related_name='source')
|
||||||
|
|
||||||
|
|
||||||
|
class OneToOneSourceSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = OneToOneSource
|
||||||
|
exclude = ('target_source', )
|
||||||
|
|
||||||
|
|
||||||
|
class OneToOneTargetSourceSerializer(serializers.ModelSerializer):
|
||||||
|
source = OneToOneSourceSerializer()
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = OneToOneTargetSource
|
||||||
|
exclude = ('target', )
|
||||||
|
|
||||||
|
class OneToOneTargetSerializer(serializers.ModelSerializer):
|
||||||
|
target_source = OneToOneTargetSourceSerializer()
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = OneToOneTarget
|
||||||
|
|
||||||
|
|
||||||
|
class NestedOneToOneTests(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
for idx in range(1, 4):
|
||||||
|
target = OneToOneTarget(name='target-%d' % idx)
|
||||||
|
target.save()
|
||||||
|
target_source = OneToOneTargetSource(name='target-source-%d' % idx, target=target)
|
||||||
|
target_source.save()
|
||||||
|
source = OneToOneSource(name='source-%d' % idx, target_source=target_source)
|
||||||
|
source.save()
|
||||||
|
|
||||||
|
def test_one_to_one_retrieve(self):
|
||||||
|
queryset = OneToOneTarget.objects.all()
|
||||||
|
serializer = OneToOneTargetSerializer(queryset)
|
||||||
|
expected = [
|
||||||
|
{'id': 1, 'name': u'target-1', 'target_source': {'id': 1, 'name': u'target-source-1', 'source': {'id': 1, 'name': u'source-1'}}},
|
||||||
|
{'id': 2, 'name': u'target-2', 'target_source': {'id': 2, 'name': u'target-source-2', 'source': {'id': 2, 'name': u'source-2'}}},
|
||||||
|
{'id': 3, 'name': u'target-3', 'target_source': {'id': 3, 'name': u'target-source-3', 'source': {'id': 3, 'name': u'source-3'}}}
|
||||||
|
]
|
||||||
|
self.assertEquals(serializer.data, expected)
|
||||||
|
|
||||||
|
|
||||||
|
def test_one_to_one_create(self):
|
||||||
|
data = {'id': 4, 'name': u'target-4', 'target_source': {'id': 4, 'name': u'target-source-4', 'source': {'id': 4, 'name': u'source-4'}}}
|
||||||
|
serializer = OneToOneTargetSerializer(data=data)
|
||||||
|
self.assertTrue(serializer.is_valid())
|
||||||
|
obj = serializer.save()
|
||||||
|
self.assertEquals(serializer.data, data)
|
||||||
|
self.assertEqual(obj.name, u'target-4')
|
||||||
|
|
||||||
|
# Ensure (target 4, target_source 4, source 4) are added, and
|
||||||
|
# everything else is as expected.
|
||||||
|
queryset = OneToOneTarget.objects.all()
|
||||||
|
serializer = OneToOneTargetSerializer(queryset)
|
||||||
|
expected = [
|
||||||
|
{'id': 1, 'name': u'target-1', 'target_source': {'id': 1, 'name': u'target-source-1', 'source': {'id': 1, 'name': u'source-1'}}},
|
||||||
|
{'id': 2, 'name': u'target-2', 'target_source': {'id': 2, 'name': u'target-source-2', 'source': {'id': 2, 'name': u'source-2'}}},
|
||||||
|
{'id': 3, 'name': u'target-3', 'target_source': {'id': 3, 'name': u'target-source-3', 'source': {'id': 3, 'name': u'source-3'}}},
|
||||||
|
{'id': 4, 'name': u'target-4', 'target_source': {'id': 4, 'name': u'target-source-4', 'source': {'id': 4, 'name': u'source-4'}}}
|
||||||
|
]
|
||||||
|
self.assertEquals(serializer.data, expected)
|
||||||
|
|
||||||
|
def test_one_to_one_create_with_invalid_data(self):
|
||||||
|
data = {'id': 4, 'name': u'target-4', 'target_source': {'id': 4, 'name': u'target-source-4', 'source': {'id': 4}}}
|
||||||
|
serializer = OneToOneTargetSerializer(data=data)
|
||||||
|
self.assertFalse(serializer.is_valid())
|
||||||
|
self.assertEquals(serializer.errors, {'target_source': [{'source': [{'name': [u'This field is required.']}]}]})
|
||||||
|
|
||||||
|
def test_one_to_one_update(self):
|
||||||
|
data = {'id': 3, 'name': u'target-3-updated', 'target_source': {'id': 3, 'name': u'target-source-3-updated', 'source': {'id': 3, 'name': u'source-3-updated'}}}
|
||||||
|
instance = OneToOneTarget.objects.get(pk=3)
|
||||||
|
serializer = OneToOneTargetSerializer(instance, data=data)
|
||||||
|
self.assertTrue(serializer.is_valid())
|
||||||
|
obj = serializer.save()
|
||||||
|
self.assertEquals(serializer.data, data)
|
||||||
|
self.assertEqual(obj.name, u'target-3-updated')
|
||||||
|
|
||||||
|
# Ensure (target 3, target_source 3, source 3) are updated,
|
||||||
|
# and everything else is as expected.
|
||||||
|
queryset = OneToOneTarget.objects.all()
|
||||||
|
serializer = OneToOneTargetSerializer(queryset)
|
||||||
|
expected = [
|
||||||
|
{'id': 1, 'name': u'target-1', 'target_source': {'id': 1, 'name': u'target-source-1', 'source': {'id': 1, 'name': u'source-1'}}},
|
||||||
|
{'id': 2, 'name': u'target-2', 'target_source': {'id': 2, 'name': u'target-source-2', 'source': {'id': 2, 'name': u'source-2'}}},
|
||||||
|
{'id': 3, 'name': u'target-3-updated', 'target_source': {'id': 3, 'name': u'target-source-3-updated', 'source': {'id': 3, 'name': u'source-3-updated'}}}
|
||||||
|
]
|
||||||
|
self.assertEquals(serializer.data, expected)
|
||||||
|
|
||||||
|
def test_one_to_one_delete(self):
|
||||||
|
data = {'id': 3, 'name': u'target-3', 'target_source': None}
|
||||||
|
instance = OneToOneTarget.objects.get(pk=3)
|
||||||
|
serializer = OneToOneTargetSerializer(instance, data=data)
|
||||||
|
self.assertTrue(serializer.is_valid())
|
||||||
|
obj = serializer.save()
|
||||||
|
|
||||||
|
# Ensure (target_source 3, source 3) are deleted,
|
||||||
|
# and everything else is as expected.
|
||||||
|
queryset = OneToOneTarget.objects.all()
|
||||||
|
serializer = OneToOneTargetSerializer(queryset)
|
||||||
|
expected = [
|
||||||
|
{'id': 1, 'name': u'target-1', 'target_source': {'id': 1, 'name': u'target-source-1', 'source': {'id': 1, 'name': u'source-1'}}},
|
||||||
|
{'id': 2, 'name': u'target-2', 'target_source': {'id': 2, 'name': u'target-source-2', 'source': {'id': 2, 'name': u'source-2'}}},
|
||||||
|
{'id': 3, 'name': u'target-3', 'target_source': None}
|
||||||
|
]
|
||||||
|
self.assertEquals(serializer.data, expected)
|
Loading…
Reference in New Issue
Block a user