Issue
I have searched this as much as I could, read the docs, looked in various posts but i start to believe it is not possible. So I want to have a partial validation schema, for a Flask app, with marshmallow like this
from marshmallow import Schema, fields, validate
class MySchema(Schema):
product_type = fields.Str(required=True, allow_none=True)
and i want to validate a dictionary and ensure that it has the product_type
field. Now this dictionary might have any number of other fields unknown to me but I don't care, I want to partially validate that the product_type
exists. For example:
data={"product_type":"consumable","other_field1":67,"other_field2":"info"...}
this passes no matter what fields are there BUT only if product type is missing it fails. How is this done?
Solution
In the marshmallow documentation there is a section "Handling Unknown Fields", which explains how to handle unknown fields. In addition to the standard procedure, which causes a ValidationError, there is also the option to exclude fields or to include and accept them. The following example shows just one way of using it.
from marshmallow import Schema, fields, validate, INCLUDE
class MySchema(Schema):
class Meta:
unknown = INCLUDE
product_type = fields.Str(required=True, allow_none=True)
Answered By - Detlef
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.