TypeError: Object of type is not JSON serializable

TypeError: Object of type is not JSON serializable

我在 Flask 上使用 flask-marshmallow

编写了 rest

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

尝试使用 json.dumps() 和 json.loads()

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

您可能想使用 ModelSchema 而不是 Schema

class ApplicationDetailSchema(ma.ModelSchema):
    class Meta:
        model = Application
        fields = ('id', 'name', 'versions')

ModelSchema 默认将相关的外键对象转储为 id(s) 列表,这是 JSON 可序列化的。

为了使用 jsonify(),您必须使 class 可序列化,您需要进行 jsonify。添加到 class 一个类似于以下的函数:

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}

然后 jsonify 对象的反序列化版本,而不是 objetc 本身:

jsonify(result.serialize())

这个方法对我有用

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)

return jsonify([s.toDict() for s in admins])