Reputation: 7276
Marshmallow normally serializes nested children (assuming nested schema are defined). For example:
{
'id': 2,
'messages' : [
{
'id': 1,
'message': 'foo'
},
{
'id': 2,
'message': 'bar'
}
]
}
However, marshmallow-sqlalchemy causes children to simply be represented by their primary key. For example:
{
'id': 2,
'messages' : [
1,
2
]
}
How can I get marshmallow-sqlalchemy to serialize the child objects. Preferably, I should be able to specify a depth. For example: serialize to 4 layers deep, then use the uid behavior.
Ideally, this should be configurable via schema.load()
because it should be dynamic based on where the serialization began. In other words, coupling this to the schema itself doesn't make sense. However, if that's the only way to do it, I'm curious to hear a solution like that as well.
Upvotes: 2
Views: 626
Reputation: 546
You can used a Nested field to do this.
Assuming you have a schema that looks like this:
class MessageSchema(Schema):
msg_id = fields.Integer()
message = fields.String()
something = fields.String()
class ListSchema(Schema):
list_id = fields.Integer()
messages = fields.Nested(MessageSchema, only=['msg_id', 'message'])
To include only certain fields, use the only
parameter when calling Nested
(see example above for usage, where only msg_id
and message
fields are included in the serialized output).
The Marshmallow docs have a more detailed + complete example:
Upvotes: 1