0

I'm trying to serialize this object, which is a result of a join between two tables:

query_response = [(<Company 2>, <Detail 1>), (<Company 3>, <Detail 2>)]

and I'm using this schema:

class CompanyCompleteSchema(Schema):
    company = fields.Nested(CompanySchema)
    detail = fields.Nested(DetailSchema)

companies_complete_schema = CompanyCompleteSchema(many=True)

Basically, I'd like to have one schema for the join query. I'm using:

data = companies_complete_schema.dump(query_response)

It doesn't work and I can't figure out the problem. It just returns:

[{}, {}]

Any suggestion is highly appreciated. Thanks.

disgra
  • 683
  • 3
  • 6
  • 18

1 Answers1

2

many=True sets Marshmallow to iterate the list provided, and deserialize each object.

An object in that list is of the form ({}, {}). Marshmallow is expecting it to have the form {'company': {}, 'detail': {}}. So, to get this to work, you'll have to convert your query result to a dictionary before passing them to the dump method. I would expect the following to work for you...

data, errors = companies_complete_schema.dump([{'company': x[0], 'detail': x[1]} for x in query_response])
Paul Becotte
  • 9,767
  • 3
  • 34
  • 42