Define a polymorph Marshmallow schema in Python

19 Views Asked by At

Consider we have the UserSchema which contains two attributes of name and user. The issue is that I am looking for a solution to load AdminSchema or GuestSchema based on the type attribute of MainSchema.

class MainSchema(Schema):
    type = fields.Str()

class AdminSchema(MainSchema):
    role = fields.Str(required=True)

class GuestSchema(MainSchema):
    reason = fields.Str(required=True)

class UserSchema(Schema):
    name = fields.Str(required=True)
    user = fields.Nested(MainSchema, required=True)

This is a sample data.

[
   {
      "name": "john",
      "user":{
         "type": "admin",
         "role": "sales"
      }
   },
   {
      "name": "jane",
      "user":{
         "type": "guest",
         "reason": "visitor"
      }
   }
]

This is an example of the problem. I am already aware of the PolyField which I can not use for this case.

0

There are 0 best solutions below