如何将bjson结构反序列化为marshmallow模式

时间:2016-08-12 23:38:58

标签: python mongodb marshmallow

我试图将bjson结构转换为marshmallow库中的模式。

以下是棉花糖架构:

class GeneSchema(Schema):
"""description of class"""

   id_entrez = fields.Integer(required = True, error_messages={'required': "The 'id_entrez' field is requeired."})
   symbol = fields.String()

   @validates('id_entrez')
   def validate_id_entrez(self, data):
       if data <= 0:
          raise ValidationError("The 'id_entrez' field must be greater than zero.")

下面是bjson将转换为schema:

[{"symbol": "VAMP4", "_id": {"$oid": "57ae3b175a945932fcbdf41d"}, "id_entrez": 8674}, {"symbol": "CCT5", "_id": {"$oid": "57ae3b175a945932fcbdf41e"}, "id_entrez": 22948}]

请注意,bjson有&#34; _id&#34; as ObjectId - &#34; $ oid&#34;。这是因为查询的结果使用了mongodb。

拜托,有谁知道为什么不能正确地从bjson转换为marshmallow架构?

谢谢大家!

2 个答案:

答案 0 :(得分:0)

您仍然可以使用您的架构来解析MongoDB输出,只需忽略额外的“_id”字段。另一方面,如果您想要解析“_id”,只需在架构中添加额外的非必填字段。

答案 1 :(得分:0)

我不知道这个问题是否仍然有效,但我想展示我的解决方案,如何将 ObjectId 推送到 Marshmallow 架构:

我只是使用 pre processing method pre_load 将 ObjectId 转换为字符串:

@pre_load
def convert_objectid(self, in_data, **kwargs):
    if "_id" in in_data:
        in_data["_id"] = str(in_data["_id"])
    return in_data