Bring check for null fk to BaseSerializer.to_representation · encode/django-rest-framework@2ef74cf (original) (raw)

2 files changed

lines changed

Original file line number Diff line number Diff line change
@@ -778,8 +778,6 @@ def to_internal_value(self, data):
778 778 return data
779 779
780 780 def to_representation(self, value):
781 -if value is None:
782 -return None
783 781 if self.uuid_format == 'hex_verbose':
784 782 return str(value)
785 783 else:
Original file line number Diff line number Diff line change
@@ -464,9 +464,13 @@ def to_representation(self, instance):
464 464 except SkipField:
465 465 continue
466 466
467 -if attribute is None:
468 -# We skip `to_representation` for `None` values so that
469 -# fields do not have to explicitly deal with that case.
467 +# We skip `to_representation` for `None` values so that fields do
468 +# not have to explicitly deal with that case.
469 +#
470 +# For related fields with `use_pk_only_optimization` we need to
471 +# resolve the pk value.
472 +check_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else attribute
473 +if check_for_none is None:
470 474 ret[field.field_name] = None
471 475 else:
472 476 ret[field.field_name] = field.to_representation(attribute)