Issue
I'm wrote rest
on the Flask using flask-marshmallow
models.py
class Application(db.Model):
__tablename__ = 'applications'
id = db.Column(db.String(), primary_key=True)
name = db.Column(db.String())
versions = db.relationship('Version', backref='application', lazy=True)
def __repr__(self):
return '<application {}>'.format(self.name)
class Version(db.Model):
__tablename__ = 'versions'
id = db.Column(db.String(), primary_key=True)
file = db.Column(db.String(80), nullable=True)
application_id = db.Column(db.Integer, db.ForeignKey('applications.id'))
shemas.py
class ApplicationDetailSchema(ma.Schema):
class Meta:
fields = ('id', 'name', 'versions')
routes.py
@bp.route("/<id>")
def application_detail(id):
application = Application.query.get(id)
result = application_detail_schema.dump(application)
return jsonify(result)
TypeError: Object of type 'Version' is not JSON serializable
Solution
You probably want to use ModelSchema
instead of Schema
.
class ApplicationDetailSchema(ma.ModelSchema):
class Meta:
model = Application
fields = ('id', 'name', 'versions')
ModelSchema
dumps the related foreign key objects as a list of id(s) by default which is JSON serializable.
Answered By - stasiekz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.