[英]How to create sqlalchemy class with child/parent to json?
I have this model in SQLAlchemy,i going to convert this model to json model with relationship 我在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
Query SelectAll: 查询SelectAll:
Session = sessionmaker(bind=ConnectEngine())
sessiondb = Session()
c = sessiondb.query(Student).all() ?? ## How to Convert List Object To JSON
how I can do it? 我该怎么办?
I know it has been so long you asked this question.Probably this might be useful who stumble on this 我知道你问这个问题已经有很长时间了。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.