mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-26 03:23:59 +03:00
Merge pull request #2637 from mdentremont/topic/allow-serialize-unsaved-with-relations
Support serializing unsaved models with related fields.
This commit is contained in:
commit
53e1a2fcb9
|
@ -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
|
||||
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue
Block a user