marshmallow-sqlalchemy
marshmallow-sqlalchemy copied to clipboard
One model, different schemes
I have two models: Projects and Subscriptions. Each project can have multiple subscriptions (one-to-many). I started from this code:
class SubscriptionSchema(ma.ModelSchema):
class Meta:
model = Subscription
class ProjectSchema(ma.ModelSchema):
class Meta:
model = Project
But in this case I could create new subscriptions from Project but schema.dump returned just object ids.
Write (OK):
>>> project = Project.query.get(1)
>>> schema = ProjectSchema(partial=True)
>>> project, errors = schema.load({"subscriptions": [1, 2]}, instance=project)
>>> schema.dump(project).data
{'id': 1, 'subscriptions': [1, 2]}
Read (not OK):
>>> project = Project.query.get(1)
>>> schema = ProjectSchema()
>>> schema.dump(project).data
{'id': 1, 'subscriptions': [1, 2]}
To overcome that issue I created a new schema:
class ProjectSchemaNestedSubscription(ProjectSchema):
subscriptions = ma.Nested(SubscriptionSchema, many=True)
and now I'm using different schemas for different REST API endpoints:
def get(self, project_id):
schema = ProjectSchemaNestedSubscription()
...
def put(self, project_id):
schema = ProjectSchema(partial=True)
...
Is this a right way to do what I need? Or maybe it is possible to do the same using just one schema? Thanks.