Merge pull request #2637 from mdentremont/topic/allow-serialize-unsaved-with-relations

Support serializing unsaved models with related fields.
This commit is contained in:
Carlton Gibson 2015-03-08 20:22:49 +01:00
commit 53e1a2fcb9
2 changed files with 24 additions and 0 deletions

View File

@ -360,6 +360,10 @@ class ManyRelatedField(Field):
]
def get_attribute(self, instance):
# Can't have any relationships if not created
if not instance.pk:
return []
relationship = get_attribute(instance, self.source_attrs)
return relationship.all() if (hasattr(relationship, 'all')) else relationship

View File

@ -143,6 +143,16 @@ class PKManyToManyTests(TestCase):
]
self.assertEqual(serializer.data, expected)
def test_many_to_many_unsaved(self):
source = ManyToManySource(name='source-unsaved')
serializer = ManyToManySourceSerializer(source)
expected = {'id': None, 'name': 'source-unsaved', 'targets': []}
# no query if source hasn't been created yet
with self.assertNumQueries(0):
self.assertEqual(serializer.data, expected)
def test_reverse_many_to_many_create(self):
data = {'id': 4, 'name': 'target-4', 'sources': [1, 3]}
serializer = ManyToManyTargetSerializer(data=data)
@ -296,6 +306,16 @@ class PKForeignKeyTests(TestCase):
self.assertFalse(serializer.is_valid())
self.assertEqual(serializer.errors, {'target': ['This field may not be null.']})
def test_foreign_key_with_unsaved(self):
source = ForeignKeySource(name='source-unsaved')
expected = {'id': None, 'name': 'source-unsaved', 'target': None}
serializer = ForeignKeySourceSerializer(source)
# no query if source hasn't been created yet
with self.assertNumQueries(0):
self.assertEqual(serializer.data, expected)
def test_foreign_key_with_empty(self):
"""
Regression test for #1072