From dc1aacf2c93b95805122b74c57e9a44ba09b8f6a Mon Sep 17 00:00:00 2001 From: Joa Riski Date: Sat, 2 Apr 2022 09:14:02 +0300 Subject: [PATCH] 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. --- rest_framework/serializers.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 389680517..0bfce3c6b 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -519,7 +519,10 @@ class Serializer(BaseSerializer, metaclass=SerializerMetaclass): if check_for_none is None: ret[field.field_name] = None else: - ret[field.field_name] = field.to_representation(attribute) + try: + ret[field.field_name] = field.to_representation(attribute) + except SkipField: + continue return ret