如何使用棉花糖序列化MongoDB ObjectId? [英] How can I serialize a MongoDB ObjectId with Marshmallow?

查看:119
本文介绍了如何使用棉花糖序列化MongoDB ObjectId?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用棉花糖和mongoengine在Flask上构建API.当我拨打电话并且应该对ID进行序列化时,会出现以下错误:

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:

TypeError: ObjectId('54c117322053049ba3ef31f3') is not JSON serializable

我看到了与其他库一起重写ObjectId的方式.我还没有用棉花糖弄清楚,有人知道怎么做吗?

I saw some ways with other libraries to override the way the ObjectId is treated. I haven't figured it out with Marshmallow yet, does anyone know how to do that?

我的模特是:

class Process(db.Document):
    name = db.StringField(max_length=255, required=True, unique=True)
    created_at = db.DateTimeField(default=datetime.datetime.now, required=True)

我的序列化器:

class ProcessSerializer(Serializer):
    class Meta:
        fields = ("id", "created_at", "name")

视图:

class ProcessView(Resource):
    def get(self, id):
        process = Process.objects.get_or_404(id)
        return ProcessSerializer(process).data

推荐答案

当您仅将Meta.fields传递给模式时,棉花糖会尝试为每个属性选择一个字段类型.由于它不知道ObjectId是什么,因此将其传递给序列化的dict.当您尝试将其转储到JSON时,它不知道ObjectId是什么,并引发错误.为了解决这个问题,您需要告诉棉花糖ID使用哪个字段.可以将 BSON ObjectId 转换为字符串,因此请使用String字段.

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')

您还可以告诉棉花糖ObjectId类型使用哪个字段,这样就不必每次都添加该字段.

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

这篇关于如何使用棉花糖序列化MongoDB ObjectId?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆