I have many schemas which have some list fields, and I want all my list fields in my schemas have a feature, that is load a None into [] automatically. So when I operate with advanced class object, I don't need to worry about it is a None or a list.
This feature cannot be simply implemented by override _deserialize, because _deserialize will not be called if input value is None. (but _serialize will be called if attribute value is None, which is different behavior as _deserialize)
One way to implement this feature, is to add @post_load to each Schama, which needs lot of repeat code.
Another way to solve the problem, is to override deserialize in fields.List, which is not the recommended way to subclass Field
### Optional List & Set
# None, [] --load()-> []
# None, [] --dump()-> []
class SafeList(List):
def _serialize(self, value, attr, obj):
result = super(SafeList, self)._serialize(value, attr, obj)
return [] if result is None else result
def deserialize(self, value, attr=None, data=None): # or override _validate_missing, None -load-> []
result = super(SafeList, self).deserialize(value, attr, data)
return [] if result is None else result
I have many schemas which have some list fields, and I want all my list fields in my schemas have a feature, that is load a
Noneinto[]automatically. So when I operate with advanced class object, I don't need to worry about it is aNoneor alist.This feature cannot be simply implemented by override
_deserialize, because_deserializewill not be called if input value isNone. (but_serializewill be called if attribute value isNone, which is different behavior as_deserialize)One way to implement this feature, is to add
@post_loadto each Schama, which needs lot of repeat code.Another way to solve the problem, is to override
deserializeinfields.List, which is not the recommended way to subclassField