在使用冒号的模型中,我想使某些字段成为可选的。
我很熟悉使用missing=colander.drop,但只有在定义了SchemaNode时才能使用。
如果使用自定义类(例如customeClass = CustomClass() )定义字段,如何将其作为可选的?
下面是片段:
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发布于 2017-10-07 20:30:33
为了使定制的Class对象成为可选对象,我们可以传递相同的missing=colander.drop作为构造函数参数。
示例:
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 differencehttps://stackoverflow.com/questions/46624780
复制相似问题