Skip to content

required=False and default is not empty no Longer Allows KeyError #2785

Closed
@cancan101

Description

Currently I have a field:

is_foo = serializers.BooleanField(source='app_metadata.is_foo', required=False)

which works fine to parse a dict looking like:
{ }, {'app_metadata':{}} or {'app_metadata': {'is_foo': True}}.

If I then change the Field to:

is_foo = serializers.BooleanField(source='app_metadata.is_foo', required=False, default=False)

I can no longer handle: { } or {'app_metadata':{}} which seems counter intuitive / wrong.

The offending code:

    def get_attribute(self, instance):
...
        try:
            return get_attribute(instance, self.source_attrs)
        except (KeyError, AttributeError) as exc:
            if not self.required and self.default is empty:
                raise SkipField()
...
            raise type(exc)(msg)

I would think that a missing field should be OK regardless of whether or not there is a default. The only difference should be that the default is inserted when missing.

I get the same issue with the Field:

is_foo = serializers.BooleanField(source='app_metadata.is_foo', default=False)

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions