diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 7e04e7e47e3..2b7906a593e 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -280,7 +280,7 @@ def get_url(self, obj, view_name, request, format): attributes are not configured to correctly match the URL conf. """ # Unsaved objects will not yet have a valid URL. - if hasattr(obj, 'pk') and obj.pk is None: + if hasattr(obj, 'pk') and obj.pk in (None, ''): return None lookup_value = getattr(obj, self.lookup_field) diff --git a/tests/test_relations.py b/tests/test_relations.py index 24087839489..f49e4ed143c 100644 --- a/tests/test_relations.py +++ b/tests/test_relations.py @@ -87,6 +87,19 @@ def test_pk_representation(self): assert representation == self.instance.pk.int +class TestHyperlinkedRelatedField(APISimpleTestCase): + def setUp(self): + self.instance = MockObject(pk=1, name='foo') + self.field = serializers.HyperlinkedRelatedField( + view_name='example', read_only=True) + self.field.reverse = mock_reverse + self.field._context = {'request': True} + + def test_representation_unsaved_object_with_non_nullable_pk(self): + representation = self.field.to_representation(MockObject(pk='')) + assert representation is None + + class TestHyperlinkedIdentityField(APISimpleTestCase): def setUp(self): self.instance = MockObject(pk=1, name='foo')