Search code examples
pythonmany-to-manysqlalchemy

How to remove all items from many-to-many collection in SqlAlchemy?


when I need to remove an object from declarative ORM many-to-many relationship, I am supposed to do this:

blogpost.tags.remove(tag)

Well. What am I supposed to do if I need to purge all these relations (not only one)? Typical situation: I'd like to set a new list of tags to my blogpost. So I need to...:

  1. Remove all existing relations between that blogpost and tags.
  2. Set new relations and create new tags if they don't exist.

Of course, there could be a better way of doing this. In that case please let me know.


Solution

  • This is the standard Python idiom for clearing a list – assigning to the “entire list” slice:

    blogpost.tags[:] = []
    

    Instead of the empty list, you may want assign the new set of tags directly.

    blogpost.tags[:] = new_tags
    

    SQLAlchemy's relations are instrumented attributes, meaning that they keep the interface of a list (or set, dict, etc), but any changes are reflected in the database. This means that anything you can do with a list is possible with a relation, while SQLA transparently listens to the changes and updates the database accordingly.