2017-10-07 2 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 
関連する問題