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) 3TypeError: Object of type 'Version' is not JSON serializable
4 Answers
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.
In order to use jsonify() you have to make serializable the class you need to jsonify. Add to that class a function similar to the following:
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')) def serialize(self): return {"id": self.id, "file": self.file, "application_id": self.application_id} And then jsonify de serializaed version of the object, and not the objetc itself:
jsonify(result.serialize()) This method work for me
class User(db.Model, Timestamp): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(20), nullable= False) email = db.Column(db.String(40), unique = True, nullable= False) def toDict(self): return dict(id=self.id, name=self.id email=self.email) and
return jsonify([s.toDict() for s in admins]) 1Try with json.dumps() and json.loads()