How to delete records from many-to-many (secondary) table in SQLAlchemy?

Try this:

post = db.session.query(Post).get(1)
post.tags = []
db.session.commit()

Here we are redefining the collection post.tags to the empty array and committing the changes. To explain this I’ll refer to the SQLAlchemy docs:

Collections in SQLAlchemy are transparently instrumented. Instrumentation means that normal operations on the collection are tracked and result in changes being written to the database at flush time.

So SQLAlchemy keeps track of the changes we make to the collection post.tags and updates it on commit.

If we had only one tag (say sometag) we could use the remove method like this:

post = db.session.query(Post).get(1)
post.tags.remove(sometag)
db.session.commit()

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)