mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-10 19:56:59 +03:00
Nested serializers now support nullable relationships, plus test. Fixes #384
This commit is contained in:
parent
250a7231d3
commit
923f81d269
|
@ -16,6 +16,10 @@ Major version numbers (x.0.0) are reserved for project milestones. No major poi
|
|||
|
||||
## 2.1.x series
|
||||
|
||||
### Master
|
||||
|
||||
* Bugfix: Nested serializers now support nullable relationships.
|
||||
|
||||
### 2.1.13
|
||||
|
||||
**Date**: 28th Dec 2012
|
||||
|
|
|
@ -307,6 +307,9 @@ class BaseSerializer(Field):
|
|||
if is_simple_callable(getattr(obj, 'all', None)):
|
||||
return [self.to_native(item) for item in obj.all()]
|
||||
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
return self.to_native(obj)
|
||||
|
||||
@property
|
||||
|
|
|
@ -32,6 +32,20 @@ class ForeignKeyTargetSerializer(serializers.ModelSerializer):
|
|||
model = ForeignKeyTarget
|
||||
|
||||
|
||||
# Nullable ForeignKey
|
||||
|
||||
class NullableForeignKeySource(models.Model):
|
||||
name = models.CharField(max_length=100)
|
||||
target = models.ForeignKey(ForeignKeyTarget, null=True, blank=True,
|
||||
related_name='nullable_sources')
|
||||
|
||||
|
||||
class NullableForeignKeySourceSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
depth = 1
|
||||
model = NullableForeignKeySource
|
||||
|
||||
|
||||
class ReverseForeignKeyTests(TestCase):
|
||||
def setUp(self):
|
||||
target = ForeignKeyTarget(name='target-1')
|
||||
|
@ -65,3 +79,24 @@ class ReverseForeignKeyTests(TestCase):
|
|||
]}
|
||||
]
|
||||
self.assertEquals(serializer.data, expected)
|
||||
|
||||
|
||||
class NestedNullableForeignKeyTests(TestCase):
|
||||
def setUp(self):
|
||||
target = ForeignKeyTarget(name='target-1')
|
||||
target.save()
|
||||
for idx in range(1, 4):
|
||||
if idx == 3:
|
||||
target = None
|
||||
source = NullableForeignKeySource(name='source-%d' % idx, target=target)
|
||||
source.save()
|
||||
|
||||
def test_foreign_key_retrieve_with_null(self):
|
||||
queryset = NullableForeignKeySource.objects.all()
|
||||
serializer = NullableForeignKeySourceSerializer(queryset)
|
||||
expected = [
|
||||
{'id': 1, 'name': u'source-1', 'target': {'id': 1, 'name': u'target-1'}},
|
||||
{'id': 2, 'name': u'source-2', 'target': {'id': 1, 'name': u'target-1'}},
|
||||
{'id': 3, 'name': u'source-3', 'target': None},
|
||||
]
|
||||
self.assertEquals(serializer.data, expected)
|
||||
|
|
Loading…
Reference in New Issue
Block a user