How to serialize SqlAlchemy result to JSON?

后端 未结 27 1887
说谎
说谎 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

    Use the built-in serializer in SQLAlchemy:

    from sqlalchemy.ext.serializer import loads, dumps
    obj = MyAlchemyObject()
    # serialize object
    serialized_obj = dumps(obj)
    
    # deserialize object
    obj = loads(serialized_obj)
    

    If you're transferring the object between sessions, remember to detach the object from the current session using session.expunge(obj). To attach it again, just do session.add(obj).

提交回复
热议问题