Support SkipField in to_representation

Allow a broader usage of the `SkipField` exception within Serializers, making it possible to skip a field from being included when `to_representation` is called on the field level. Previously this has already been supported for `Field.get_attribute`, but not `Field.to_representation`.

For an example, this change allows raising a `SkipField` exception in a function called by `SerializerMethodField` in order to omit that field conditionally.
This commit is contained in:
Joa Riski 2022-04-02 09:14:02 +03:00 committed by GitHub
parent df92e57ad6
commit dc1aacf2c9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -519,7 +519,10 @@ class Serializer(BaseSerializer, metaclass=SerializerMetaclass):
if check_for_none is None: if check_for_none is None:
ret[field.field_name] = None ret[field.field_name] = None
else: else:
try:
ret[field.field_name] = field.to_representation(attribute) ret[field.field_name] = field.to_representation(attribute)
except SkipField:
continue
return ret return ret