Honza Javorek
Honza Javorek

Reputation: 8816

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.

Upvotes: 15

Views: 12331

Answers (2)

ᅠᅠᅠ
ᅠᅠᅠ

Reputation: 67010

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.

Upvotes: 27

Xuan Hu
Xuan Hu

Reputation: 886

Confrimed for what Two-Bit Alchemist has reported.

blogpost.tags[:] = new_tags

will complain about

TypeError: 'AppenderBaseQuery' object does not support item assignment

But

blogpost.tags = new_tags

seems to work fine.

Upvotes: 15

Related Questions