Skip to content

Commit 125334d

Browse files
committed
Fix empty pk detection in HyperlinkRelatedField.get_url
This implementation allows detection of empty values that are non-nullable, allowing the field to return None values for such cases
1 parent a568d16 commit 125334d

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

rest_framework/relations.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,7 @@ def get_url(self, obj, view_name, request, format):
280280
attributes are not configured to correctly match the URL conf.
281281
"""
282282
# Unsaved objects will not yet have a valid URL.
283-
if hasattr(obj, 'pk') and obj.pk is None:
283+
if hasattr(obj, 'pk') and obj.pk in (None, ''):
284284
return None
285285

286286
lookup_value = getattr(obj, self.lookup_field)

tests/test_relations.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,19 @@ def test_pk_representation(self):
8787
assert representation == self.instance.pk.int
8888

8989

90+
class TestHyperlinkedRelatedField(APISimpleTestCase):
91+
def setUp(self):
92+
self.instance = MockObject(pk=1, name='foo')
93+
self.field = serializers.HyperlinkedRelatedField(
94+
view_name='example', read_only=True)
95+
self.field.reverse = mock_reverse
96+
self.field._context = {'request': True}
97+
98+
def test_representation_unsaved_object_with_non_nullable_pk(self):
99+
representation = self.field.to_representation(MockObject(pk=''))
100+
assert representation is None
101+
102+
90103
class TestHyperlinkedIdentityField(APISimpleTestCase):
91104
def setUp(self):
92105
self.instance = MockObject(pk=1, name='foo')

0 commit comments

Comments
 (0)