I have an issue in Flask application with serialization model object that has a many to many relationship with extra field stored in association table. I would like to have a serialized data looking like so:
{
"id": "123",
"name": "name",
"mobile": "phone number",
"interest": [1, 2, 3]
"_embedded": {
"interest": [
{
"id": 1,
"name": "ECONOMIC",
"active": true,
},
{
"id": 2,
"name": "POETRY",
"active": true,
},
{
"id": 3,
"name": "SPORT",
"active": false,
},
]
}
}
For now I managed to prepare a neccessary models as below:
class OwnerInterests(db.Model):
owner_id = db.Column(db.Integer, db.ForeignKey('owners.id'), primary_key=True)
interest_id = db.Column(db.Integer, db.ForeignKey('interests.id'), primary_key=True)
active = db.Column(db.Boolean)
interest = db.relationship('Interests', back_populates='owners')
owner = db.relationship('Owners', back_populates='interests')
class Owners(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
mobile = db.Column(db.String)
interests = db.relationship('OwnersInterests', back_populates='owner')
class Interests(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
owners = db.relationship('OwnersInterests', back_populates='interest')
but now I'm wondering about approach, how to prepare a sqlalchemy query with marshmallow schema. Any thoughts?
EDIT :
My current marshmallow schema looks like:
class InterestSchema(ma.ModelSchema):
class Meta:
model = Interests
exclude = ('owners',)
class OwnerSchema(ma.ModelSchema):
interests = ma.Nested(InterestSchema, many=True)
class Meta:
model = Owners