赞
踩
用sqlalchemy做关联查询时发现不支持用自带的json属性得到json字符串,写了一个方法利用dir来遍历属性,转成json
DBSession = sessionmaker(bind=engine)
session = DBSession()
records = session.query(A.name, B.name).filter(A.aid == B.aid).all()
session.close()
def convert_to_json(inst):
d = dict()
for c in dir(inst):
if(not c.startswith('_') and c not in ['count','index','keys']):
d[c] = getattr(inst, c)
if(type(d[c]) == datetime.datetime):
d[c] = d[c].strftime("%Y-%m-%d %H:%M:%S")
return json.dumps(d)
records_json = '[' + ','.join([convert_to_json(record) for record in records]) + ']'
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。