Python SQLModel - Truncate table or delete all and get number of rows

Viewed 774

Using Python SQLModel, I want to truncate a table, or remove all rows, and get the number of deleted rows, in the most SQLModel standar way. How can I do this? I am using this:

        with Session(engine) as session:
            count = session.exec(delete(MyModel)).fetchall()
            session.commit()

But it raises an error:

ResourceClosedError('This result object does not return rows. It has been closed automatically.')

I have also tried scalar() and fetchone() instead of fetchall() without success.

1 Answers
with Session(engine) as session:
    statement = delete(MyModel)
    result = session.exec(statement)
    session.commit()
    print(result.rowcount)

Matched Row Counts

Related