棉花糖EmbeddedDocument不起作用

时间:2018-11-07 01:26:06

标签: mongoengine marshmallow flask-restplus

我用flask-restplusmongoengie制作了一个简单的Board api。

也可以使用marshmallow序列化数据。

下面的代码现在可以工作了。

[模型]

class Article(Document):
    no = SequenceField()
    subject = StringField(required=True)
    content = StringField(required=True)
    userid = StringField(required=True)
    comments = ListField(EmbeddedDocumentField(Comment))
    created_at = DateTimeField(default=datetime.datetime.now())
    updated_at = DateTimeField(default=datetime.datetime.now())


class Comment(EmbeddedDocument):
    content = StringField(required=True)
    userid = StringField(required=True)
    created_at = DateTimeField(default=datetime.datetime.now())

[序列化器]

class CommentSchema(Schema):
    content = fields.String()
    userid = fields.String()
    created_at = fields.DateTime()

class ArticleSchema(Schema):
    comments = CommentSchema(many=True)
    class Meta:
        fields = ('no', 'subject', 'content', 'userid', 'comments', 'created_at', 'updated_at')

我定义了遵循模型的模型。

ArticleSchema中,为了显示注释,我定义了comments = CommentSchema(many=True)并将其插入到fields中。

获取文章功能在这里。

def get_all_articles():
    articles = Article.objects.all()
    data, errors = ArticleListSchema(many=True).dump(articles)
    return data

但是当我访问它时,它会发生内部错误并抛出这样的错误消息。

TypeError: Object of type Comment is not JSON serializable

在Google中搜索后,我发现了一些感兴趣的功能Nested。 (https://marshmallow.readthedocs.io/en/3.0/nesting.html

所以我修改了架构。

class ArticleSchema(Schema):
    no = fields.Integer()
    subject = fields.String()
    content = fields.String()
    userid = fields.String()
    comments = fields.Nested(CommentSchema())
    created_at = fields.DateTime()
    updated_at = fields.DateTime()

({comments = fields.Nested(CommentSchema()

但是它也不能正常工作。

[结果]

{
    "subject": "string",
    "content": "string",
    "userid": "string",
    "updated_at": "2018-11-06T17:04:55.197000+00:00",
    "no": 20,
    "created_at": "2018-11-06T17:04:55.197000+00:00",
    "comments": {}
}

我已经插入2条注释,mongodb结果为

> db.article.find()
{ "_id" : ObjectId("5be14bb61b48d9113e3d1413"), "no" : 20, "subject" : "string", "content" : "string", "userid" : "string", "comments" : [ { "content" : "cosdadas", "userid" : "123123", "created_at" : ISODate("2018-11-06T17:34:44.199Z") }, { "content" : "Second comment", "userid" : "john", "created_at" : ISODate("2018-11-06T17:34:44.199Z") } ], "created_at" : ISODate("2018-11-06T17:04:55.197Z"), "updated_at" : ISODate("2018-11-06T17:04:55.197Z") }

但是在API中,没有显示注释。只是空的{}。

这里有什么解决办法吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

[已解决]

更改

comments = fields.Nested(CommentSchema())

comments = fields.Nested(CommentSchema, many=True),效果很好。