我在SQLAlchemy中有这个模型,我将把这个模型转换为关系
的json模型class Test(Base):
__tablename__ = 'reltest'
id = Column(Integer, primary_key=True)
name = Column(String(50))
fullname = Column(String(50))
password = Column(String(50))
parent_id = Column(Integer, ForeignKey('reltest.id'),index=True)
children = relationship(lambda: Student, remote_side=[id])
hashid = None
查询SelectAll:
Session = sessionmaker(bind=ConnectEngine())
sessiondb = Session()
c = sessiondb.query(Student).all() ?? ## How to Convert List Object To JSON
我该怎么做?
答案 0 :(得分:0)
我知道你问这个问题的时间已经很久了。可能这个人偶然发现了这个问题
from json import JSONEncoder, dumps
class DatabaseObjectEncoder(JSONEncoder):
def default(self, o):
if isinstance(o, Base):
return o.get_dict()
return super(DatabaseObjectEncoder, self).default(o)
def json_encode_db_obj(obj):
return dumps(obj, cls=DatabaseObjectEncoder)
Session = sessionmaker(bind=ConnectEngine())
sessiondb = Session()
c = json_encode_db_obj(sessiondb.query(Student).all()) # c should have a json now