SQLAlchemy many-to-many orphan deletion

后端 未结 4 2117
梦如初夏
梦如初夏 2021-02-15 13:06

I\'m trying to use SQLAlchemy to implement a basic users-groups model where users can have multiple groups and groups can have multiple users.

When a group becomes empty

相关标签:
4条回答
  • 2021-02-15 13:08

    The way I've generally handled this is to have a function on your user or group called leave_group. When you want a user to leave a group, you call that function, and you can add any side effects you want into there. In the long term, this makes it easier to add more and more side effects. (For example when you want to check that someone is allowed to leave a group).

    0 讨论(0)
  • 2021-02-15 13:12

    I had the same problem about 3 months ago, i have a Post/Tags relation and wanted to delete unused Tags. I asked on irc and SA's author told me that cascades on many-to-many relations are not supported, which kind of makes sense since there is no "parent" in many-to-many.

    But extending SA is easy, you can probably use a AttributeExtension to check if the group became empty when is removed from a User and delete it from there.

    0 讨论(0)
  • 2021-02-15 13:18

    I think you want cascade='save, update, merge, expunge, refresh, delete-orphan'. This will prevent the "delete" cascade (which you get from "all") but maintain the "delete-orphan", which is what you're looking for, I think (delete when there are no more parents).

    0 讨论(0)
  • 2021-02-15 13:27

    Could you post a sample of your table and mapper set up? It might be easier to spot what is going on.

    Without seeing the code it is hard to tell, but perhaps there is something wrong with the direction of the relationship?

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