marshmallow icon indicating copy to clipboard operation
marshmallow copied to clipboard

Convert fields to optional if parent's field has a specific value

Open lightspot21 opened this issue 3 years ago • 0 comments

Hello,

I am trying to define the following schema (pseudo-ish code):

class Parent(marshmallow.Schema):
    action = marshmallow.fields.EnumField(required=True)
    parameters = marshmallow.fields.Nested(Child, required=True)

class Child(marshmallow.Schema)
    param1 = marshmallow.fields.Str()
    param2 = marshmallow.fields.Int()
    # so on and so forth....

What I want the schema above to do is:

  • In case "action" has a specific value, all fields of the Child schema must be optional. However, if one passes a field that is not in Child, the validation must still fail.
  • In all other cases, all fields of Child must be required.

So far I've found this which does something similar, but I can't find a way to modify it for the case of a nested schema. Is this even possible to do with marshmallow?

Any ideas? Thanks in advance!

lightspot21 avatar Jan 28 '22 15:01 lightspot21