Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.
In concrete terms, the following serializer returns the data as seen below
class DrfSerializer(serializers.Serializer):
value = serializers.IntegerField(required=...)
DRF 3.7.3
required=True
required=False
data = {'value': 1}
{'value': 1}
{'value': 1}
data = {'value': None}
{'value': None}
{'value': None}
data = {}
KeyError(u"Got KeyError when...
{}
When using the following serpy 0.2.0 serializer I get the results below
class SerpySerializer(serpy.DictSerializer):
value = serpy.Field(required=...)
serpy 0.2.0
required=True
required=False
data = {'value': 1}
{'value': 1}
{'value': 1}
data = {'value': None}
TypeError('Field {0} is required', 'value')
{}
data = {}
KeyError('value',)
KeyError('value',)
For reference, this is the output from serpy 0.1.1
serpy 0.1.1
required=True
required=False
data = {'value': 1}
{'value': 1}
{'value': 1}
data = {'value': None}
{'value': None}
{'value': None}
data = {}
KeyError('value',)
KeyError('value',)
As seen in the tables, PR #38 does the following things
breaks cases that previously matched DRF behavior
adds no new cases that match DRF behavior
breaks any serializers that wanted to return None.
For these reasons I'd like to suggest #38 be reverted.
As a result of #38 serpy the following things happen when
None
is returned from aMethodField
required=True
(default), serialization throws an exceptionrequired=False
, the key and value are not included in the output dictionary.I'm using MethodField because it's a concrete example. I believe the same thing happens with most (if not all) other fields.
As you might expect, this breaks any use case of serpy that needs to return None.
The django rest framework docs state
In concrete terms, the following serializer returns the data as seen below
required=True
required=False
data = {'value': 1}
{'value': 1}
{'value': 1}
data = {'value': None}
{'value': None}
{'value': None}
data = {}
KeyError(u"Got KeyError when...
{}
When using the following serpy 0.2.0 serializer I get the results below
required=True
required=False
data = {'value': 1}
{'value': 1}
{'value': 1}
data = {'value': None}
TypeError('Field {0} is required', 'value')
{}
data = {}
KeyError('value',)
KeyError('value',)
For reference, this is the output from serpy 0.1.1
required=True
required=False
data = {'value': 1}
{'value': 1}
{'value': 1}
data = {'value': None}
{'value': None}
{'value': None}
data = {}
KeyError('value',)
KeyError('value',)
As seen in the tables, PR #38 does the following things
None
.For these reasons I'd like to suggest #38 be reverted.