2017-10-07 155 views
0

我想使用漏勺制作的模型中的某些字段是可选的。
我熟悉使用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 

回答

0

为了使自定义类对象作为可选的,我们可以通过相同的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 difference