mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-02-03 13:14:30 +03:00
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
This commit is contained in:
parent
ef8e7f168f
commit
e34a34e90b
|
@ -280,7 +280,7 @@ class HyperlinkedRelatedField(RelatedField):
|
||||||
attributes are not configured to correctly match the URL conf.
|
attributes are not configured to correctly match the URL conf.
|
||||||
"""
|
"""
|
||||||
# Unsaved objects will not yet have a valid URL.
|
# 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
|
return None
|
||||||
|
|
||||||
lookup_value = getattr(obj, self.lookup_field)
|
lookup_value = getattr(obj, self.lookup_field)
|
||||||
|
|
|
@ -87,6 +87,18 @@ class TestProxiedPrimaryKeyRelatedField(APISimpleTestCase):
|
||||||
assert representation == self.instance.pk.int
|
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):
|
class TestHyperlinkedIdentityField(APISimpleTestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
self.instance = MockObject(pk=1, name='foo')
|
self.instance = MockObject(pk=1, name='foo')
|
||||||
|
|
Loading…
Reference in New Issue
Block a user