How to delete rows from a table using an SQLAlchemy query without ORM?

前端 未结 2 1073
挽巷
挽巷 2020-12-15 15:18

I\'m writing a quick and dirty maintenace script to delete some rows and would like to avoid having to bring my ORM classes/mappings over from the main project. I have a qu

2条回答
  •  被撕碎了的回忆
    2020-12-15 16:16

    When you call delete() from a query object, SQLAlchemy performs a bulk deletion. And you need to choose a strategy for the removal of matched objects from the session. See the documentation here.

    If you do not choose a strategy for the removal of matched objects from the session, then SQLAlchemy will try to evaluate the query’s criteria in Python straight on the objects in the session. If evaluation of the criteria isn’t implemented, an error is raised.

    This is what is happening with your deletion.

    If you only want to delete the records and do not care about the records in the session after the deletion, you can choose the strategy that ignores the session synchronization:

    address_table = Table('address', metadata, autoload=True)
    addresses = session.query(address_table).filter(address_table.c.retired == 1)
    addresses.delete(synchronize_session=False)
    

提交回复
热议问题