棉花糖-mongoengine:输出转储值缺少“无”字段

时间:2019-03-07 05:03:20

标签: mongoengine

我的项目使用flask + mongoengine + 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
}

我该怎么办?

1 个答案:

答案 0 :(得分: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': []}