From 2ef74cfa61d6f52a2a5c32151a052488d5d7e9e2 Mon Sep 17 00:00:00 2001 From: Carlton Gibson Date: Sun, 13 Mar 2016 20:39:19 +0100 Subject: [PATCH] Bring check for null fk to `BaseSerializer.to_representation` --- rest_framework/fields.py | 2 -- rest_framework/serializers.py | 10 +++++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index c700b85e85..6d5962c8ec 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -778,8 +778,6 @@ def to_internal_value(self, data): return data def to_representation(self, value): - if value is None: - return None if self.uuid_format == 'hex_verbose': return str(value) else: diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index b95bb7fa68..625d32644b 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -464,9 +464,13 @@ def to_representation(self, instance): except SkipField: continue - if attribute is None: - # We skip `to_representation` for `None` values so that - # fields do not have to explicitly deal with that case. + # We skip `to_representation` for `None` values so that fields do + # not have to explicitly deal with that case. + # + # For related fields with `use_pk_only_optimization` we need to + # resolve the pk value. + check_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else attribute + if check_for_none is None: ret[field.field_name] = None else: ret[field.field_name] = field.to_representation(attribute)