Skip to content
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
4 changes: 2 additions & 2 deletions rest_framework/relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,8 @@ def get_attribute(self, instance):
if self.use_pk_only_optimization() and self.source_attrs:
# Optimized case, return a mock object only containing the pk attribute.
try:
instance = get_attribute(instance, self.source_attrs[:-1])
value = instance.serializable_value(self.source_attrs[-1])
attribute_instance = get_attribute(instance, self.source_attrs[:-1])
value = attribute_instance.serializable_value(self.source_attrs[-1])
if is_simple_callable(value):
# Handle edge case where the relationship `source` argument
# points to a `get_relationship()` method on the model
Expand Down
18 changes: 17 additions & 1 deletion tests/test_relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import pytest
from _pytest.monkeypatch import MonkeyPatch
from django.conf.urls import url
from django.core.exceptions import ImproperlyConfigured
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.test import override_settings
from django.utils.datastructures import MultiValueDict

Expand Down Expand Up @@ -167,6 +167,22 @@ def test_representation_unsaved_object_with_non_nullable_pk(self):
representation = self.field.to_representation(MockObject(pk=''))
assert representation is None

def test_serialize_empty_relationship_attribute(self):
class TestSerializer(serializers.Serializer):
via_unreachable = serializers.HyperlinkedRelatedField(
source='does_not_exist.unreachable',
view_name='example',
read_only=True,
)

class TestSerializable:
@property
def does_not_exist(self):
raise ObjectDoesNotExist

serializer = TestSerializer(TestSerializable())
assert serializer.data == {'via_unreachable': None}

def test_hyperlinked_related_lookup_exists(self):
instance = self.field.to_internal_value('http://example.org/example/foobar/')
assert instance is self.queryset.items[0]
Expand Down