How can I serialize a MongoDB ObjectId with Marshmallow?

前端 未结 4 1466
你的背包
你的背包 2021-02-14 07:48

I\'m building and API on top of Flask using marshmallow and mongoengine. When I make a call and an ID is supposed to be serialized I receive the following error:



        
4条回答
  •  北荒
    北荒 (楼主)
    2021-02-14 08:02

    When you just pass Meta.fields to a schema, Marshmallow tries to pick a field type for each attribute. Since it doesn't know what an ObjectId is, it just passes it on to the serialized dict. When you try to dump this to JSON, it doesn't know what an ObjectId is and raises an error. To solve this, you need to tell Marshmallow what field to use for the id. A BSON ObjectId can be converted to a string, so use a String field.

    from marshmallow import Schema, fields
    
    class ProcessSchema(Schema):
        id = fields.String()
    
        class Meta:
            additional =  ('created_at', 'name')
    

    You can also tell Marshmallow what field to use for the ObjectId type so that you don't have to add the field each time.

    from bson import ObjectId
    from marshmallow import Schema, fields
    
    Schema.TYPE_MAPPING[ObjectId] = fields.String
    

提交回复
热议问题