只能对单个数据操作,
import json
import datetime
#对单个模型操作
def model_to_dict(model, fields=None):
"""
将Flask SQLAlchemy的模型对象转换为字典类型
:param: model : 模型对象
:param: fields : 需要获取的字段列表,默认为 None,获取全部字段
:return: 返回字典类型
"""
if fields is None:
# 获取所有列名
columns = [column.name for column in model.__table__.columns]
# 排除掉relationships 设置的反向查询字段
relations = getattr(model.__class__, '__mapper__').relationships
exclude_cols = [rel.key for rel in relations]
# print(exclude_cols,'要剔除的反向查询字段')
#拿到所有列名-排除的列名
cols = set(columns) - set(exclude_cols)
fields = list(cols)
obj_dict = {}
for field in fields:
if field not in model.__dict__:
continue
value = model.__dict__[field]
#1、对时间字段进行操作
if isinstance(value, datetime.datetime):
#字段类型是datetime的,格式化
value = value.strftime('%Y-%m-%d %H:%M:%S')
if isinstance(value,datetime.date):
#字段类型是date的,格式化
value = value.strftime('%Y-%m-%d')
#2、将所有可以进行序列化的进行序列化
if isinstance(value,str):
try:
value = json.loads(value)
except Exception as _:
pass
obj_dict[field] = value
return obj_dict
使用:
class AuthorView(MethodView):
def get(self):
author = models.AuthorModel.query.first()
dic = model_to_dict(author,fields=['id','name','address'])
return {'code':200,'dic':dic}
代码:
#对数据集操作
def model_to_dict_list(queryset,fields=None):
ret = []
for obj in queryset:
dic = model_to_dict(obj,fields=fields)
ret.append(dic)
return ret
使用:
class AuthorView(MethodView):
def get(self):
authors = models.AuthorModel.query.all()
dic = model_to_dict_list(authors,fields=['id','name','address'])
return {'code':200,'dic':dic}