I'm creating a Flask API using SQLAlchemy models. I don't want to define a schema for every model I have, I don't want to do this every time:
class EntrySchema(ma.ModelSchema):
class Meta:
model = Entry
I would like each model to have a schema, so it can easily dump itself. Creating a default Schema and setting the Schema.Meta.model didn't work:
class Entry(db.Model):
__tablename__ = 'entries'
id = db.Column(db.Integer, primary_key=True)
started_at = db.Column(db.DateTime)
ended_at = db.Column(db.DateTime)
description = db.Column(db.Text())
def __init__(self, data):
for key in data:
setattr(self, key, data[key])
self.Schema = Schema
self.Schema.Meta.model = self.__class__
def dump(self):
schema = self.Schema()
result = schema.dump(self)
return result
class Schema(ma.ModelSchema):
class Meta:
pass
Why is a generic Schema with the model overwritten different than a Schema with the model declared?