Flask Marshmallow serialize many to many relation with extra field
This schema gives you something quite similar to your specification:
from marshmallow import Schema, fieldsclass InterestSchema(Schema): class Meta: fields = ('id', 'name') ordered = Trueclass OwnerInterestSchema(Schema): interest = fields.Nested(InterestSchema) class Meta: fields = ('id', 'interest', 'active') ordered = Trueclass OwnerSchema(Schema): interests = fields.Nested(OwnerInterestSchema, many=True) class Meta: fields = ('id', 'name', 'mobile', 'interests') ordered = True
You can then serialise your data like this (note that my model doesn't have exactly the same name as yours):
>>> from app.serialisation import OwnerSchema>>> from app.models import Owner>>> data = OwnerSchema().dump(Owner.query.get(1))>>> from marshmallow import pprint>>> pprint(data){"id": 1, "name": "John", "mobile": "07123456789", "interests": [{"interest": {"id": 1, "name": "Economics"}, "active": true}, {"interest": {"id": 2, "name": "Poetry"}, "active": true}, {"interest": {"id": 3, "name": "Sport"}, "active": false}]}
Let me just indent that output so you can see what's going on:
{ "id": 1, "name": "John", "mobile": "07123456789", "interests": [ { "interest": { "id": 1, "name": "Economics" }, "active": true }, { "interest": { "id": 2, "name": "Poetry" }, "active": true }, { "interest": { "id": 3, "name": "Sport" }, "active": false } ]}
You can adapt this to use the model-plus-exclude paradigm if you want. And if you really want that "_embedded"
field in your JSON, you probably need a custom field, as described here.
You could also use custom fields to flatten your interests and put the "active"
field on the same level as "id"
and "name"
, but I think that would be misleading.