SQLAlchemy delete doesn't cascade

前端 未结 1 1250
遥遥无期
遥遥无期 2020-12-05 00:01

My User model has a relationship to the Address model. I\'ve specified that the relationship should cascade the delete operation. However, when I q

相关标签:
1条回答
  • 2020-12-05 00:36

    You have the following...

    db.session.query(User).filter(User.my_id==1).delete()
    

    Note that after "filter", you are still returned a Query object. Therefore, when you call delete(), you are calling delete() on the Query object (not the User object). This means you are doing a bulk delete (albeit probably with just a single row being deleted)

    The documentation for the Query.delete() method that you are using says...

    The method does not offer in-Python cascading of relationships - it is assumed that ON DELETE CASCADE/SET NULL/etc. is configured for any foreign key references which require it, otherwise the database may emit an integrity violation if foreign key references are being enforced.

    As it says, running delete in this manner will ignore the Python cascade rules that you've set up. You probably wanted to do something like..

    user = db.session.query(User).filter(User.my_id==1).first()
    db.session.delete(user)
    

    Otherwise, you may wish to look at setting up the cascade for your database as well.

    0 讨论(0)
提交回复
热议问题