def model_to_dict(object):
return {c.name: getattr(object, c.name) for c in object.__table__.columns}
#將一組數(shù)據(jù)轉(zhuǎn)為list
def scalars_to_list(object):
return [model_to_dict(c) for c in object]
class Sysdict(Base,SerializerMixin):
__bind_key__ = 'forest_fire_control_manage'
__tablename__ = 'sys_dict'
id = Column(Integer, primary_key=True)
code = Column(String(100))
parent_code = Column(String(100))
name = Column(String(60))
seq = Column(Integer)
dict_type = Column(String(100))
if __name__ == "__main__":
app = create_app()
with app.app_context():
res = Sysdict.query.all()
#將單個數(shù)據(jù)轉(zhuǎn)為dict
# for c in res[0].__table__.columns:
# print(c.name)
# print(getattr(res[0], c.name))
print(scalars_to_list(res)
結(jié)果示例:
[{'id': 1, 'code': 'class_land_type', 'parent_code': 'root', 'name': '地類', 'seq': 0, 'dict_type': 'class_info'}, {'id': 37, 'code': 'forest_type', 'parent_code': 'root', 'name': '林種', 'seq': 0, 'dict_type': 'class_info'}, {'id': 64, 'code': 'forest_right', 'parent_code': 'root', 'name': '權(quán)屬', 'seq': 0, 'dict_type': 'class_info'}, {'id': 68, 'code': 'terrain', 'parent_code': 'root', 'name': '地形', 'seq': 0, 'dict_type': 'class_info'}, {'id': 75, 'code': 'slope_position', 'parent_code': 'root', 'name': '坡位', 'seq': 0, 'dict_type': 'class_info'}, {'id': 82, 'code': 'slope_direction', 'parent_code': 'root', 'name': '坡向', 'seq': 0, 'dict_type': 'class_info'}, {'id': 84, 'code': 'soil_type', 'parent_code': 'root', 'name': '土壤類型', 'seq': 0, 'dict_type': 'class_info'}, {'id': 86, 'code': 'forest_protect_level', 'parent_code': 'root', 'name': '林地保護等級', 'seq': 0, 'dict_type': 'class_info'}, {'id': 91, 'code': 'domaint_tree_type', 'parent_code': 'root', 'name': '優(yōu)勢樹種', 'seq': 0, 'dict_type': 'class_info'}, {'id': 117, 'code': 'origin', 'parent_code': 'root', 'name': '起源', 'seq': 0, 'dict_type': 'class_info'}, {'id': 124, 'code': 'age', 'parent_code': 'root', 'name': '齡組', 'seq': 0, 'dict_type': 'class_info'}]
另外:
res = Sysdict.query.all() 這種寫法已經(jīng)不被推薦了,
推薦的是scalar_one() 獲取一行,scalars()獲取多行
user = db.session.execute(db.select(User).filter_by(username=username)).scalar_one()
users = db.session.execute(db.select(User).order_by(User.username)).scalars()
一般的
json.dumps(users)
或者
jsonify(users)
都會出現(xiàn)錯誤:Object of type ScalarResult is not JSON serializable
所以,使用這兩個方法解決:
def model_to_dict(object):
return {c.name: getattr(object, c.name) for c in object.table.columns}
#將一組數(shù)據(jù)轉(zhuǎn)為list
def scalars_to_list(object):
return [model_to_dict? for c in object]文章來源:http://www.zghlxwxcb.cn/news/detail-636860.html
ref:https://blog.csdn.net/weixin_53632096/article/details/129986590文章來源地址http://www.zghlxwxcb.cn/news/detail-636860.html
到了這里,關(guān)于【flask sqlalchmey】一次性將返回的列表對象或者 一行數(shù)據(jù)對象轉(zhuǎn)成dict---flask-sqlalchemy輸出json格式數(shù)據(jù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!