marshmallow-mongoengine:输出转储值缺少“无”字段

问题描述 投票:0回答:1

我的项目使用flask + mongoengine + marshmallow,当我使用marshmallow序列化模型时,返回值缺少字段,缺少的字段值为None。当使用Django序列化字段时,None值仍然是输出模型

class Author(db.Document):
    name = db.StringField()
    gender = db.IntField()
    books = db.ListField(db.ReferenceField('Book'))

    def __repr__(self):
        return '<Author(name={self.name!r})>'.format(self=self)


class Book(db.Document):
    title = db.StringField()

串行

class AuthorSchema(ModelSchema):
    class Meta:
        model = Author


class BookSchema(ModelSchema):
    class Meta:
        model = Book

author_schema = AuthorSchema()

当我这样做:

author = Author(name="test1")
>>> author.save()
<Author(name='test1')>
>>> author_schema.dump(author)
MarshalResult(data={'id': '5c80a029fe985e42fb4e6299', 'name': 'test1'}, errors={})
>>> 

不返回books字段我希望返回

{
    "name":"test1",
    "books": None
}

我该怎么办?

mongoengine
1个回答
0
投票

当我查看marshmallow-mongoengine库的源代码时,我在测试文件中找到了解决方案model_skip_values=()

def test_disable_skip_none_field(self):
        class Doc(me.Document):
            field_empty = me.StringField()
            list_empty = me.ListField(me.StringField())
        class DocSchema(ModelSchema):
            class Meta:
                model = Doc
                model_skip_values = ()
        doc = Doc()
        data, errors = DocSchema().dump(doc)
        assert not errors
        assert data == {'field_empty': None, 'list_empty': []}
© www.soinside.com 2019 - 2024. All rights reserved.