根据官方documentation,我尝试以json格式获取Vehicle类的所有实例
Session = sessionmaker(bind=engine)
session = Session()
from models import Vehicle
from marshmallow_sqlalchemy import ModelSchema
class VehicleShema(ModelSchema):
class Meta:
model = Vehicle
vehicles = session.query(Vehicle).all()
vehicle_schema = VehicleShema()
session.add(vehicles)
session.commit()
dump_data = vehicle_schema.dump(vehicles)
print(dump_data)
但是出现错误
raise exc.UnmappedInstanceError(instance)
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.list' is not mapped
我认为问题可能出在queriset vehicles = session.query(Vehicle).all()
的定义上,但我找不到其他解决方法。
然后我只调用一个实例vehicles = session.query(Vehicle).first()
都可以正常工作。
错误回溯
Traceback (most recent call last):
File "/home/y700/projects/viastart/sqlalchemy/orm/session.py", line 1955, in add
state = attributes.instance_state(instance)
AttributeError: 'list' object has no attribute '_sa_instance_state'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "get_vehisle_by_id.py", line 11, in <module>
session.add(vehicles)
File "/home/y700/projects/viastart/sqlalchemy/orm/session.py", line 1957, in add
raise exc.UnmappedInstanceError(instance)
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.list' is not mapped
答案 0 :(得分:1)
您没有指定是否要将vechiles
序列化为一个集合,即一个列表。
vehicle_schema = VehicleShema(many=True)
这应该可以解决问题。请参阅棉花糖docs上发布的示例。
答案 1 :(得分:1)
根据我的评论使用schema.dump(vehicles, many=True)
:
要进行扩展,您可能最终想要使用如下所示的实用程序:
def dumpData(load_object, schema, many=False):
try:
answer = schema.dump(load_object, many=many)
except ValidationError as errors:
raise InvalidDump(errors, status_code=400)
return answer
class InvalidDump(Exception):
"""error for dumping data"""
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
"""include marshmallow validation errors in response"""
rv = dict(self.payload or ())
rv['message'] = self.message.messages
return rv
然后为每个数据转储创建具有该棉花糖模式的版本。
def dumpVehicle(load_object, many=False):
return dumpData(load_object, schema=vehicle_schema_full, many=many)