From a15cda4be4e14f5de5db41a4f664ee95107e0984 Mon Sep 17 00:00:00 2001 From: Yuri Prezument Date: Sat, 31 Aug 2013 17:10:15 +0300 Subject: [PATCH 1/2] Regression test for #1072 --- rest_framework/tests/test_relations_pk.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/rest_framework/tests/test_relations_pk.py b/rest_framework/tests/test_relations_pk.py index e2a1b8152..3815afdd8 100644 --- a/rest_framework/tests/test_relations_pk.py +++ b/rest_framework/tests/test_relations_pk.py @@ -283,6 +283,15 @@ class PKForeignKeyTests(TestCase): self.assertFalse(serializer.is_valid()) self.assertEqual(serializer.errors, {'target': ['This field is required.']}) + def test_foreign_key_with_empty(self): + """ + Regression test for #1072 + + https://github.com/tomchristie/django-rest-framework/issues/1072 + """ + serializer = NullableForeignKeySourceSerializer() + self.assertEqual(serializer.data['target'], None) + class PKNullableForeignKeyTests(TestCase): def setUp(self): From 745ebeca77e6bcbec4eb94fb98206d6913e3d049 Mon Sep 17 00:00:00 2001 From: Yuri Prezument Date: Sat, 31 Aug 2013 17:20:49 +0300 Subject: [PATCH 2/2] Handle case where obj=None in PKRelatedField.field_to_native() Fixes #1072 --- rest_framework/relations.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 3ad16ee5e..35c00bf1d 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -264,7 +264,7 @@ class PrimaryKeyRelatedField(RelatedField): # RelatedObject (reverse relationship) try: pk = getattr(obj, self.source or field_name).pk - except ObjectDoesNotExist: + except (ObjectDoesNotExist, AttributeError): return None # Forward relationship