[英]fastAPI SQLmodel MultipleResultsFound: Multiple rows were found when exactly one was required
This is my delete function.这是我删除的 function。
def delete_session(self,session_id: int, db):
with Session(engine) as session:
statement = select(db).where(db.session == session_id)
results = session.exec(statement)
sess = results.one()
print("sess: ", sess)
if not sess:
raise HTTPException(status_code=404, detail="Session not found")
session.delete(sess)
session.commit()
return {"Session Deleted": True}
I want to delete all records where session_id matches.我想删除 session_id 匹配的所有记录。 But its throwing following error
MultipleResultsFound: Multiple rows were found when exactly one was required
但它抛出以下错误
MultipleResultsFound: Multiple rows were found when exactly one was required
How can i delete multiple rows at once.我怎样才能一次删除多行。
I tried using我尝试使用
sess = results.all()
but it say但它说
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.list' is not mapped
Thanks谢谢
Currently, you are trying to delete several data items, except that session.delete()
only takes a single value, not a list of values.当前,您正在尝试删除多个数据项,但
session.delete()
仅采用单个值,而不是值列表。
You are using results.one()
probably thinking that you can isolate your answers and return only one.您正在使用
results.one()
可能认为您可以隔离您的答案并只返回一个。 However, it is explained in the documentation that if multiple entries are found in the parameter passed to one()
then it will throw a MultipleResultsFound
exception, hence your error.但是,文档中解释说,如果在传递给
one()
的参数中找到多个条目,那么它将抛出MultipleResultsFound
异常,因此会出现错误。
Indeed, your statement returns a list, so multiple values.实际上,您的语句返回一个列表,因此有多个值。
In order to delete all your elements, you should not use one()
but simply iterate with a for
loop on your results
and delete one by one, your data, as follows:为了删除所有元素,您不应该使用
one()
而是简单地用for
循环迭代您的results
并一个一个地删除您的数据,如下所示:
def delete_session(self, session_id: int, db):
with Session(engine) as session:
statement = select(db).where(db.session == session_id)
results = session.exec(statement).all()
for sess in results:
session.delete(sess)
session.commit()
return {"Session Deleted": True}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.