aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMatt d'Entremont2015-03-04 17:36:03 -0400
committerMatt d'Entremont2015-03-06 12:50:37 -0400
commitfb58ef043cc39d900bb8389855f07087cb0d7920 (patch)
tree79e80017c1f7535c7d9a592888ef6c0aa352e039
parentf7917928c080aa0b055cbfc588f61ec01f16771c (diff)
downloaddjango-rest-framework-fb58ef043cc39d900bb8389855f07087cb0d7920.tar.bz2
Add support for serializing models with m2m related fields
- In both ManyRelatedField, provide an empty return when trying to access a relation field if the instance in question has no PK (so likely hasn't been inserted yet) - Add relevant tests - Without these changes, exceptions would be raised when trying to serialize the uncreated models as it is impossible to query relations without a PK - Add test to ensure RelatedField does not regress as currently supports being serialized with and unsaved model
-rw-r--r--rest_framework/relations.py4
-rw-r--r--tests/test_relations_pk.py20
2 files changed, 24 insertions, 0 deletions
diff --git a/rest_framework/relations.py b/rest_framework/relations.py
index 0b7c9d86..3a966c5b 100644
--- a/rest_framework/relations.py
+++ b/rest_framework/relations.py
@@ -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
diff --git a/tests/test_relations_pk.py b/tests/test_relations_pk.py
index f872a8dc..ca43272b 100644
--- a/tests/test_relations_pk.py
+++ b/tests/test_relations_pk.py
@@ -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