6

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

unknown
  • 252
  • 3
  • 12
  • 37

5 Answers5

3

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())
alexdefelipe
  • 169
  • 2
  • 8
3

Use @dataclass decorator

on version 3.7+, u can use the dataclass decorator:

from dataclasses import dataclass

@dataclass
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)

then, jsonify works fine.

songofhawk
  • 91
  • 7
1

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.

Valiant
  • 88
  • 1
  • 10
stasiekz
  • 1,775
  • 5
  • 22
0

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])
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 24 '22 at 14:10
-6

Try with json.dumps() and json.loads()

https://docs.python.org/3/library/json.html