Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy delete limit rows

How can I delete last 10 rows from my query?

I have query:

query = session.query(MyTableClass) \ 
.filter(MyTableClass.country=='USA') \ 
.order_by(MyTableClass.id.asc()) \ 
.limit(10)

How can I delete 10 rows only?

I tried: query.delete() - error: Can't call Query.update() or Query.delete() when limit() has been called

session.delete(query) - error: Class 'sqlalchemy.orm.query.Query' is not mapped

like image 596
maxrudometkin Avatar asked Sep 05 '19 00:09

maxrudometkin


Video Answer


1 Answers

You can't delete a query that has a limit() on it, but you can delete one with a filter(). So you:

  • make your query into a subquery with the limit(10) on it. Just put a .subquery() on the end
  • make a second query that filters for your subquery and you can delete that.

If this seems silly to you, you're not alone. I believe this was reported as a bug a few years ago and never got fixed. It has to do with the object type limit() returns.

like image 59
Ambiwlans Avatar answered Oct 03 '22 07:10

Ambiwlans