How to serialize SqlAlchemy result to JSON?

后端 未结 27 1876
说谎
说谎 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:14

    You could just output your object as a dictionary:

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

    And then you use User.as_dict() to serialize your object.

    As explained in Convert sqlalchemy row object to python dict

提交回复
热议问题