How to serialize SqlAlchemy result to JSON?

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

    Maybe you can use a class like this

    from sqlalchemy.ext.declarative import declared_attr
    from sqlalchemy import Table
    
    
    class Custom:
        """Some custom logic here!"""
    
        __table__: Table  # def for mypy
    
        @declared_attr
        def __tablename__(cls):  # pylint: disable=no-self-argument
            return cls.__name__  # pylint: disable= no-member
    
        def to_dict(self) -> Dict[str, Any]:
            """Serializes only column data."""
            return {c.name: getattr(self, c.name) for c in self.__table__.columns}
    
    Base = declarative_base(cls=Custom)
    
    class MyOwnTable(Base):
        #COLUMNS!
    

    With that all objects have the to_dict method

提交回复
热议问题