小编Edd*_* E.的帖子

使用“data_key”定义的 Marshmallow 字段与使用“attribute”定义的字段(标识符相反?)之间有什么区别?

使用定义marshmallow.Schema名称字段的 (v3.0+)和使用 定义名称字段的另一个(v3.0+)之间有区别吗?fooattribute="bar"bardata_key="foo"

两者似乎都以相同的方式序列化和反序列化字典和其他简单对象:

import marshmallow

class MySchema1(marshmallow.Schema):
    foo = marshmallow.fields.String(attribute="bar")

class MySchema2(marshmallow.Schema):
    bar = marshmallow.fields.String(data_key="foo")

schema1 = MySchema1()
schema2 = MySchema2()

dictionary = {"bar": "hello world"}
assert schema1.dump(dictionary) == schema2.dump(dictionary)
assert schema1.load(schema1.dump(dictionary)) == schema2.load(schema2.dump(dictionary))

class Thingy:
    def __init__(self):
        self.bar = "hello world"

instance = Thingy()
assert schema1.dump(instance) == schema2.dump(instance)
assert schema1.load(schema1.dump(instance)) == schema2.load(schema2.dump(instance))
Run Code Online (Sandbox Code Playgroud)

以上通过。目前这不会在我的项目中造成任何错误,但我很好奇有什么区别!提前致谢。

python schema attributes marshmallow

7
推荐指数
1
解决办法
4109
查看次数

标签 统计

attributes ×1

marshmallow ×1

python ×1

schema ×1