jsonmodels
jsonmodels copied to clipboard
ListField does not respect value None (default value is []).
Basically, there is no way to get rid of a ListField element in output json. For other fields, you set them to None and it will be removed from output of to_struct(), but this does not apply to ListField. I reckon, ideally, None value should remove it from json and [] should put a [] in json. It looks like the default value for ListField is [] so there is no way for to_struct() to understand whether user set the field to None, [] or left it unassigned. Also, it looks like 'required' and 'nullable' properties are ignored for ListField.
You can override to_struct method in your model, check all ListFields for len == 0 and skip it like it is doing for None values.
def to_struct(self):
self.validate()
resp = {}
for _, name, field in self.iterate_with_name():
value = field.__get__(self)
_type = type(field)
if value is None or (isinstance(field, fields.ListField) and len(value) == 0):
continue
value = field.to_struct(value)
resp[name] = value
return resp