klen / marshmallow-peewee

Peewee ORM integration with the marshmallow (de)serialization library.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[idea] Filter for non required fields with empty incoming data

ak4nv opened this issue · comments

Hi!
Sometimes we've got an empty field value in incoming data. And if this field maps on database model field which has default value or null param is set to True, empty value is not good for us. Not always, but very often. I use this code in my ModelSchema wrapper:

class ModelSchema(_ModelSchema):

    @pre_load
    def drop_empty_fields(self, item):
        field_names = tuple(item.keys())
        for k in field_names:
            field = self.fields.get(k)
            if field and not field.required and not item[k]:
                item.pop(k)

For example: field is DateField(default=datetime.date.today), incoming data value is "" (empty string). Would be nice to drop this field from incoming dataset and save the instance with default value. Now we get an error Not a valid date.
I suggest to add a some boolean initial param (for ex. filter) for manage this case.
What do you think?

In continuous of this idea:

from marshmallow_peewee import ModelSchema as _ModelSchema
from marshmallow import pre_load


class ModelSchema(_ModelSchema):

    @pre_load
    def drop_empty_fields(self, obj):
        for x in self.Meta.drop_empty_fields:
            if x in obj and not obj[x]:
                obj.pop(x)

    class Meta(_ModelSchema.Meta):
        drop_empty_fields = ()