Added overidable ModelSerializer.check_for_none

This commit is contained in:
Anthony Monthe 2018-01-25 14:16:10 +00:00
parent 1664588500
commit 3a8752d8ab

View File

@ -479,6 +479,16 @@ class Serializer(BaseSerializer):
return ret 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): def to_representation(self, instance):
""" """
Object instance -> Dict of primitive datatypes. Object instance -> Dict of primitive datatypes.
@ -492,13 +502,7 @@ class Serializer(BaseSerializer):
except SkipField: except SkipField:
continue continue
# We skip `to_representation` for `None` values so that fields do if self.check_for_none(attribute) is None:
# 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 ret[field.field_name] = None
else: else:
ret[field.field_name] = field.to_representation(attribute) ret[field.field_name] = field.to_representation(attribute)