SQLAlchemy对象转字典,解决SQLAlchemy对象返回为空的问题

目录

一、在模型文件中为Base对象加上一个to_dict方法

二、使用


 

一、在模型文件中为Base对象加上一个to_dict方法

Base = declarative_base()


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


Base.to_dict = to_dict

二、使用

# 返回对象
one = session.query().one()
return one.to_dict()

# 返回对象列表
all= session.query().all()
return [i.to_dict() for i in all]