I am having problems deleting records from PostTag
table that contains Post
and Tag
column. This is my relation table:
Try to remove objects from the collection instead:
post[0].tags.clear()
You could also remove individual items:
post[0].tags.remove(posttag)
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()