okelet
okelet

Reputation: 756

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

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.

Upvotes: 5

Views: 5185

Answers (1)

r-m-n
r-m-n

Reputation: 15120

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

Matched Row Counts

Upvotes: 8

Related Questions