booby
booby copied to clipboard
choices, defaults and None values
The API I am accessing returns JSON with a field that will return null
for almost all fields. If I POST/PUT this model back into the API, it will interpret the null
values as if they are unset.
There is an exception to this. One specific String
field (however, there is no reason why in future this could not apply to other value types) in which a POST/PUT operation must be one of x values.
As a result, I apply the choices
options and also a default
The field is current defined as:
option = fields.String(choices=['FOO', 'BAR', 'ANY', 'NONE'], default='NONE')
Imagine the following though.
import json
from booby import Model, fields
class TestModel(Model):
fake = fields.String()
option = fields.String(choices=['FOO', 'BAR', 'ANY', 'NONE'], default='NONE')
test_json_b = "{'fake': 'AMZ',}"
test_json_c = "{'fake': 'AMZ', 'option': null}"
tb = json.loads(test_json_b)
tc = json.loads(test_json_c)
mod_a = TestModel()
mod_b = TestModel(**ta)
mod_c = TestModel(**tc)
assert mod_a.option == 'NONE'
assert mod_a.is_valid == True
assert mod_b.option == 'NONE'
assert mod_b.is_valid == True
assert mod_c.option == None # Undesired
assert mod_c.is_valid == False # Undesired
Is there a method to remove the undesired behaviour above, in which a null
breaks the option
field?
I have added None
to the list of choices for the field, but then this also makes the default
redundant, given that the API returns null
everytime it is unset.