SQLAlchemy: How do you delete multiple rows without querying

后端 未结 3 1589
小鲜肉
小鲜肉 2021-01-31 02:11

I have a table that has millions of rows. I want to delete multiple rows via an in clause. However, using the code:

session.query(Users).filter(Users.id.in_(sub         


        
相关标签:
3条回答
  • 2021-01-31 03:00

    Yep! You can call delete() on the table object with an associated where clause.

    Something like this:

    stmt = Users.__table__.delete().where(Users.id.in_(subquery...))
    

    (and then don't forget to execute the statement: engine.execute(stmt))

    source

    0 讨论(0)
  • 2021-01-31 03:01

    To complete dizzy's answer:

    delete_q = Report.__table__.delete().where(Report.data == 'test')
    db.session.execute(delete_q)
    db.session.commit()
    
    0 讨论(0)
  • 2021-01-31 03:07

    The below solution also works, if developers do not want to execute a plain vanilla query.

    session.query(Users).filter(Users.id.in_(subquery....)).delete(synchronize_session=False)
    
    0 讨论(0)
提交回复
热议问题