0

This is my delete 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. But its throwing following error 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

Talha Anwar
  • 2,699
  • 4
  • 23
  • 62

1 Answers1

0

Currently, you are trying to delete several data items, except that session.delete() only takes a single value, not a list of values.

You are using results.one() probably thinking that you can isolate your answers and return only 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.

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:


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}

fchancel
  • 2,396
  • 6
  • 21