0

My project uses flask+mongoengine+marshmallow,When I used marshmallow to serialize the model, the returned value lacked field, and the missing field value was None.When using Django to serialize fields, the None value is still output model

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

serializers

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


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

author_schema = AuthorSchema()

When I do this:

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

not return the books field I hope to return

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

what should I do?

1 Answers1

0

When I looked at the source code of the marshmallow-mongoengine library, I found the solution model_skip_values=() in the tests file.

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': []}