diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 33da0bad0..e2af08a51 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -479,6 +479,16 @@ class Serializer(BaseSerializer): return ret + def check_for_none(self, attribute): + # 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. + if isinstance(attribute, PKOnlyObject): + return attribute.pk + return attribute + def to_representation(self, instance): """ Object instance -> Dict of primitive datatypes. @@ -492,13 +502,7 @@ class Serializer(BaseSerializer): except SkipField: continue - # 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: + if self.check_for_none(attribute) is None: ret[field.field_name] = None else: ret[field.field_name] = field.to_representation(attribute)