作者:mobiledu2502909131 | 来源:互联网 | 2023-10-12 19:10
marshmallow's fields.Field has two options.
I wonder
is the hook (or default value) for serialization, and
is the hook for deserialization.
with many=True option, default is ok
when serialization, default option is correctly, I feel.
1 2 3 4 5 6 7 8 9
| python
from marshmallow import fields, Schema
class S(Schema):
nums = fields.Integer(many=True, default=[1, 2, 3])
print(S().dump({}).data)
# {'nums': [1, 2, 3]} |
with many=true option, missing is uncomfortable behavior
But, when deserialization, current marshmallow's behavior is not good. Maybe, I have misunderstanding for missing option. Although, using missing option with
, treating default value as collection is better, I think.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| python
from marshmallow import fields, Schema
class S(Schema):
nums = fields.Integer(many=True, missing="[1, 2, 3]")
# this is error.
print(S().load({}))
# UnmarshalResult(data={}, errors={'nums': ['Not a valid integer.']})
# if missing's value is 1, error is not raised. but, this is not good, at least me.
class S2(Schema):
nums = fields.Integer(many=True, missing="1")
print(S2().load({}))
# UnmarshalResult(data={'nums': 1}, errors={}) |
该提问来源于开源项目:marshmallow-code/marshmallow
OK. I've misunderstood the meaning about
, for a collection value, using fields.List instead of many option. I missed fields.List .
, Thank you for replying correct answer.