Marshmallow Deserialize Nested Schema

Hi everyone, I am trying to find a way to deserialize a json object using Marshmallow.

I have a schema that is like this

class CustomerDTO(BaseDTO):
    first_name: str = fields.Str(required=True)
    last_name: str = fields.Str(required=True)
    address: AddressDTO = fields.Nested(AddressDTOSchema, required=True)

class CustomerDTOSchema(Schema, CustomerDTO)

class AddressDTO(BaseDTO):
    street_name_one: str = fields.Str(required=True)
    street_name_two: str = fields.Str(required=False)
    state: str = fields.Str(required=True)
    zip: str = fields.Str(required=True)
class AddressDTOSchema(Schema, AddressDTO)

def GetJson():
    customer_dto_data = request.get_json()
    customer_dto_schema = CustomerDTOSchema().load(customer_dto_data)
    customer_dto = CustomerDTO(**customer_dto_schema)
   print(customer_dto) # prints out the entire object in dictionary format
   print(customer_dto.first_name) # works great
   print(customer_dto.address.street_name_one) # I get -> AttriuteError: 'dict' object has no attribute 'street_name_one'
 print(customer_dto.address) # prints out the values for address just fine.

Is there a way for me to help the object be deserialized correctly?

Hi! Unfortunately, this seems to be an issue specific to Mashmellow, so unless someone here happens to be familiar with it, you are probably better off reaching out to a marshmellow-specific support channel instead. Best of luck!

I don’t have full experience with vanilla Marshmallow, but it doesn’t look like the constructor of BaseDTO can handle nested models. I don’t know what BaseDTO even is.

In vanilla Marshmallow, you have to declare deserialisation using the post_load decorator on methods of all of your schema classes: see Quickstart — marshmallow 3.14.1 documentation

I do have experience with marshmallow-dataclasses, which reduces boilerplate and improves the typing experience. You’ll probably want Python 3.10 with keyword-only fields though

1 Like