How to serialize SqlAlchemy result to JSON?

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

    Flask-JsonTools package has an implementation of JsonSerializableBase Base class for your models.

    Usage:

    from sqlalchemy.ext.declarative import declarative_base
    from flask.ext.jsontools import JsonSerializableBase
    
    Base = declarative_base(cls=(JsonSerializableBase,))
    
    class User(Base):
        #...
    

    Now the User model is magically serializable.

    If your framework is not Flask, you can just grab the code

提交回复
热议问题