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

前端 未结 2 954
轻奢々
轻奢々 2020-12-30 03:18

I am having problems deleting records from PostTag table that contains Post and Tag column. This is my relation table:



        
相关标签:
2条回答
  • 2020-12-30 03:26

    Try to remove objects from the collection instead:

    post[0].tags.clear()
    

    You could also remove individual items:

    post[0].tags.remove(posttag)
    
    0 讨论(0)
  • 2020-12-30 03:53

    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()
    
    0 讨论(0)
提交回复
热议问题