在Python Flask中使用SQLAlchemy查询的数据必须像这样一个个设置健名返回吗?
能不能像Nodejs或者Java那样直接把查询的数据返回给接口

在Python Flask中使用SQLAlchemy查询的数据必须像这样一个个设置健名返回吗?
能不能像Nodejs或者Java那样直接把查询的数据返回给接口

可以像这样设置,就不用一个一个写了
from sqlalchemy.orm import class_mapper
def format_data(data):
# 格式化数据,处理json无法序列化的数据
if isinstance(data, datetime.datetime):
return data.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(data, datetime.date):
return data.strftime("%Y-%m-%d")
elif isinstance(data, Decimal):
return float(data)
else:
return data
class BaseModel(db.Model):
# 作为模型类基类,继承as_dict方法
__abstract__ = True
def as_dict(self):
return {p.key: format_data(getattr(self, p.key)) for p in class_mapper(self.__class__).iterate_properties}