Skip to content
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

Fix empty pk detection in HyperlinkRelatedField.get_url #3962

Merged
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
2 changes: 1 addition & 1 deletion rest_framework/relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
12 changes: 12 additions & 0 deletions tests/test_relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,18 @@ def test_pk_representation(self):
assert representation == self.instance.pk.int


class TestHyperlinkedRelatedField(APISimpleTestCase):
def setUp(self):
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')
Expand Down