I want to make certain fields in a model made using colander to be optional.
I am familiar with using missing=colander.drop
but that only works when SchemaNode is defined.
In case, the field is defined using a custom class, say customeClass = CustomClass()
, how to make this as optional?
Below is the snippet:
import colander
class Image(colander.MappingSchema):
url = colander.SchemaNode(colander.String())
width = colander.SchemaNode(colander.Int())
height = colander.SchemaNode(colander.Int())
class Post(colander.MappingSchema):
id = colander.SchemaNode(colander.Int())
text = colander.SchemaNode(colander.String())
score = colander.SchemaNode(colander.Int())
created_time = colander.SchemaNode(colander.Int())
attachedImage = Image() # I want to make this as optional
In order to make the custom Class object as optional, we can pass same missing=colander.drop
as constructor parameter.
Example:
import colander
class Image(colander.MappingSchema):
url = colander.SchemaNode(colander.String())
width = colander.SchemaNode(colander.Int())
height = colander.SchemaNode(colander.Int())
class Post(colander.MappingSchema):
id = colander.SchemaNode(colander.Int())
text = colander.SchemaNode(colander.String())
score = colander.SchemaNode(colander.Int())
created_time = colander.SchemaNode(colander.Int())
attachedImage = Image(missing=colander.drop) # The difference