我在字典里定义了一个对象的另一部分。我希望在反序列化对象时自动解析键。我怎样才能以惯用的方式在棉花糖中达到这种效果呢?在
目前的解决方法是手动解析所有的引用,但这看起来很笨拙,因为棉花糖的声明性特性应该能够自动为我们完成。在
注意,Marshmallow SQLAlchemy在columns are declared as relationships“时支持这种(反)序列化,这会自动为我们做到这一点,但我想用JSON数据来实现。在
下面是我想要实现的一个例子,fields.Relationship
是一个还不存在的东西:
class UserSchema(Schema):
name = fields.String()
email = fields.Email()
friends = fields.Relationship('self', path="AddressBook.contacts", many=True)
class AddressBookSchema(Schema):
contacts = nested.Dict(keys=fields.String(), values=fields.Nested(UserSchema))
# ... create ``user`` ...
serialized_data = AddressBookSchema().dump(user)
pprint(serialized_data)
# "contacts": {
# "Steve": {
# "name": "Steve",
# "email": "steve@example.com",
# "friends": ["Mike"]
# },
# "Mike": {
# "name": "Mike",
# "email": "mike@example.com",
# "friends": []
# }
deserialized_data = UserSchema().load(result)
pprint(deserialized_data)
# "contacts": {
# "Steve": {
# "name": "Steve",
# "email": "steve@example.com",
# "friends": [ {"name": "Mike", "email": "mike@example.com"]
# },
# "Mike": {
# "name": "Mike",
# "email": "mike@example.com",
# "friends": []
# }
为什么不简单地用^{} 钩子传输中间数据:
产量:
^{pr2}$相关问题 更多 >
编程相关推荐