Skip to content

Commit 2ef74cf

Browse files
committed
Bring check for null fk to BaseSerializer.to_representation
1 parent cbb8d8d commit 2ef74cf

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

rest_framework/fields.py

-2
Original file line numberDiff line numberDiff line change
@@ -778,8 +778,6 @@ def to_internal_value(self, data):
778778
return data
779779

780780
def to_representation(self, value):
781-
if value is None:
782-
return None
783781
if self.uuid_format == 'hex_verbose':
784782
return str(value)
785783
else:

rest_framework/serializers.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -464,9 +464,13 @@ def to_representation(self, instance):
464464
except SkipField:
465465
continue
466466

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:
470474
ret[field.field_name] = None
471475
else:
472476
ret[field.field_name] = field.to_representation(attribute)

0 commit comments

Comments
 (0)