将数据库信息转化为字典类型,部分字段信息需要转换数据类型(如:datetime)
""" 将数据库内容输出为字典类型 """ db_data_list = Stu.query.filter(Stu.id >0) key = [i for i in Stu.__dict__.keys() if not i.startswith("_") and i != "value"] #获取字段 def swith_db_data(key, db_data_list): # key:字段 db_data_list: 数据库数据 data_list = [] for db_data in db_data_list: x = {} for word in key: a = eval("db_data.%s" % word) x[word] = str(a) data_list.append(x) return data_list print(swith_db_data(key, db_data_list))
输出:[{'id': '1', 'name': '张三', 'select_num': '20'}, {'id': '2', 'name': '李四', 'select_num': '0'}]