2017-07-13 21 views
0

我想指定一個模式字段wichi接受一個或多個資源。不過,我似乎只能指定一種行爲或另一種行爲。使用棉花糖指定一個或多個字段

>>> class Resource(marshmallow.Schema): 
...  data = marshmallow.fields.Dict() 
... 
>>> class ContainerSchema(marshmallow.Schema): 
...  resource = marshmallow.fields.Nested(ResourceSchema, many=True) 
... 
>>> ContainerSchema().dump({'resource': [{'data': 'DATA'}]}) 
MarshalResult(data={'resource': [{'data': 'DATA'}]}, errors={}) 

在上述例子中,必須定義一個列表。不過,我不想:

>>> ContainerSchema().dump({'resource': {'data': 'DATA'}}) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/lib64/python3.6/site-packages/marshmallow/schema.py", line 513, in dump 
    **kwargs 
    File "/lib64/python3.6/site-packages/marshmallow/marshalling.py", line 147, in serialize 
    index=(index if index_errors else None) 
    File "/lib64/python3.6/site-packages/marshmallow/marshalling.py", line 68, in call_and_store 
    value = getter_func(data) 
    File "/lib64/python3.6/site-packages/marshmallow/marshalling.py", line 141, in <lambda> 
    getter = lambda d: field_obj.serialize(attr_name, d, accessor=accessor) 
    File "/lib64/python3.6/site-packages/marshmallow/fields.py", line 252, in serialize 
    return self._serialize(value, attr, obj) 
    File "/lib64/python3.6/site-packages/marshmallow/fields.py", line 448, in _serialize 
    schema._update_fields(obj=nested_obj, many=self.many) 
    File "/lib64/python3.6/site-packages/marshmallow/schema.py", line 760, in _update_fields 
    ret = self.__filter_fields(field_names, obj, many=many) 
    File "/lib64/python3.6/site-packages/marshmallow/schema.py", line 810, in __filter_fields 
    obj_prototype = obj[0] 
KeyError: 0 

我可以有一個模式,允許單個項目或許多嗎?

回答

0

將參數作爲列表給出的觀點 - 無論是一個還是多個 - 都是這樣,模式知道如何處理它。對於架構來處理不同格式的參數,如不在列表中,你需要一個預處理器添加到模式,就像這樣:

class ContainerSchema(marshmallow.Schema): 
    resource = marshmallow.fields.Nested(ResourceSchema, many=True) 
    @pre_dump 
    def wrap_indata(self, indata): 
     if type(indata['resource']) is dict: 
      indata['resource'] = [indata['resource']]