How to serialize SqlAlchemy result to JSON?

后端 未结 27 1867
说谎
说谎 2020-11-22 09:59

Django has some good automatic serialization of ORM models returned from DB to JSON format.

How to serialize SQLAlchemy query result to JSON format?

I tried

27条回答
  •  無奈伤痛
    2020-11-22 10:07

    A more detailed explanation. In your model, add:

    def as_dict(self):
           return {c.name: str(getattr(self, c.name)) for c in self.__table__.columns}
    

    The str() is for python 3 so if using python 2 use unicode(). It should help deserialize dates. You can remove it if not dealing with those.

    You can now query the database like this

    some_result = User.query.filter_by(id=current_user.id).first().as_dict()
    

    First() is needed to avoid weird errors. as_dict() will now deserialize the result. After deserialization, it is ready to be turned to json

    jsonify(some_result)
    

提交回复
热议问题