Skip to content

Support serializing unsaved models with related fields. #2637

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 8, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions rest_framework/relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,10 @@ def to_internal_value(self, data):
]

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

Expand Down
20 changes: 20 additions & 0 deletions tests/test_relations_pk.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,16 @@ def test_many_to_many_create(self):
]
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)
Expand Down Expand Up @@ -296,6 +306,16 @@ def test_foreign_key_update_with_invalid_null(self):
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
Expand Down