marshmallow-mongoengine icon indicating copy to clipboard operation
marshmallow-mongoengine copied to clipboard

Inheritance - child classes aren't serialised properly

Open davidwneary opened this issue 7 years ago • 0 comments

I'm not sure if this is a feature request or bug.

Say I have the following Documents defined:

class Company(Document):
    products = EmbeddedDocumentListField(Product)

class Product(EmbeddedDocument):
    name = StringField()

    meta = {
        'allow_inheritance': True
    }

class ClothingProduct(Product):
    fabric = StringField()

class FoodProduct(Product):
    ingredients = ListField()

and I have a schema for Company:

class CompanySchema(Schema):
    class Meta:
        model = Company

and I run the following code:

productA = ClothingProduct(name='tshirt', fabric='cotton')
productB = FoodProduct(name='sausage', ingredients=['Pork', 'sage', 'breadcrumbs'])
company = Company(products=[productA, productB])
result = CompanySchema(company).dump()

result is:

{
"products": [
        {
          "_cls": "ClothingProduct",
          "name": "tshirt"
        },
        {
          "_cls": "FoodProduct",
          "name": "sausage"
        }
      ]
}

whereas I would expect it to be:

{
"products": [
        {
          "_cls": "ClothingProduct",
          "fabric": "cotton",
          "name": "tshirt"
        },
        {
          "_cls": "FoodProduct",
          "ingredients": ['Pork', 'sage', 'breadcrumbs'],
          "name": "sausage"
        }
      ]
}

I understand why this could be the case since when we create the schema, we only have the Product class to go off, but I wondered if there was a way around this. Perhaps leveraging .__subclasses__()? I can have a closer look myself but just wanted to check if this was something that had been considered before or if it is not expected behaviour.

Cheers Dave

davidwneary avatar Jul 04 '17 09:07 davidwneary