【flask sqlalchmey】一次性将返回的列表对象或者 一行数据对象转成dict---flask-sqlalchemy输出json格式数据


def model_to_dict(object):
    return {c.name: getattr(object, c.name) for c in object.__table__.columns}

#将一组数据转为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()
        #将单个数据转为dict
        #   for c in res[0].__table__.columns:
        #       print(c.name)
        #       print(getattr(res[0], c.name))
        print(scalars_to_list(res)
        

结果示例:

[{'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': '权属', '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': '优势树种', '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() 这种写法已经不被推荐了,
推荐的是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)

都会出现错误: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}

#将一组数据转为list
def scalars_to_list(object):
return [model_to_dict© for c in object]

ref:https://blog.csdn.net/weixin_53632096/article/details/129986590

你可能感兴趣的:(flask,flask,python,后端)