Marshmallow: Handling of NULL in Schema

Created on 23 Apr 2018  路  5Comments  路  Source: marshmallow-code/marshmallow

Hi all,

I have a Schema as such:

start_time = fields.Str()

In MariaDB this is often a NULL field.

When marshmallow serializes it, shouldn't the output be

"start_time":'', (this is desired)

instead what I get is:

"start_time":null,

Most helpful comment

It would be nice if allow_none=False forced serialization to fall back to the default value.

All 5 comments

I think the desired output would not even include start_time.

@sloria posted a way to achieve this in https://github.com/marshmallow-code/marshmallow/issues/229.

As I point out in a comment, it will also remove the field from the output if the field has allow_none=True, which is probably wrong.

It would be nice if allow_none=False forced serialization to fall back to the default value.

@lafrech That would work for me I think. I've tried your code, but it doesn't seem to help. The fields are still being generated if they don't have a value.

from marshmallow import Schema, fields, post_dump

class BaseSchema(Schema):
    @post_dump
    def null_to_empty_string(self, data):
        return {
            key: '' for key, value in data.items()
            if value is None
        }


class MySchema(BaseSchema):
    start_time = fields.DateTime()


sch = MySchema()
sch.dump({'start_time': None}).data  # {'start_time': ''}

Closing this as it is pretty old. Please comment if you're still stuck.

It would be nice if allow_none=False forced serialization to fall back to the default value.

Anyone interested in this, please open a new issue.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sloria picture sloria  路  3Comments

agatheblues picture agatheblues  路  3Comments

lupodellasleppa picture lupodellasleppa  路  3Comments

lassandroan picture lassandroan  路  3Comments

tadams42 picture tadams42  路  3Comments