marshmallow schema validation dash problem

Viewed 784

I'm using marshmallow for validate some fields of a schema.

class PlantDetailsSchema(Schema):
        name: fields.Str(required=True, validate=validate.Length(min=3)),
        sprout-time: fields.Str(required=True, validate=validate.Length(min=3)),
        full-growth: fields.Str(required=True, validate=validate.Length(min=5)),
        edible: fields.Bool(required=True)



class PlantInfoSchema(Schema):
    plant = fields.Nested(PlantDetailsSchema)
    num = fields.Int(required=True, validate=validate.Range(min=1))


def validate_json(json):
    try:
        schema = PlantInfoSchema().load(json)
        ret = schema.dump()
        return ret
    except ValidationError:
        return None

The json element to validate is: json = {'plant': {'name': 'Bonsai', 'sprout-time': '3 months', 'full-growth': '2 years', 'edible': False}, 'num': 3}

My issue is how to validate fields that contains a dash in the middle of the name (like 'sprout-time' and 'full-growth'. Do you have some ideas to solve this issue?

1 Answers

You can use the 'data_key' attribute to specify the key name with dash. Define the field name something which is valid like 'sprout_time' (could be anything) and data_key as an attribute to the field with the actual name 'sprout-time'.

class PlantDetailsSchema(Schema):
    name = fields.Str(required=True, validate=validate.Length(min=3))
    sprout_time = fields.Str(
        data_key='sprout-time',
        required=True, validate=validate.Length(min=3)
    )
    full_growth = fields.Str(
        data_key='full-growth',
        required=True, 
        validate=validate.Length(min=5)
    )
    edible = fields.Bool(required=True)
Related