title: Can not update entries with many to many relation in Flask
body: <p>I am totally new with flask and sqlalchemy. I try to make one web site just to get better understanding of flask. I have something like blog where user can create post and set multiple tags. I use flask-sqlalchemy and wtforms-alchemy. I have 2 models</p>
  
  <pre><code>association_table = db.Table('association',
      db.Column('post_id', db.Integer, db.ForeignKey('post.id')),
      db.Column('category_id', db.Integer, db.ForeignKey('category.id'))
  )
  
  class Post(db.Model):
      id = db.Column(db.Integer, primary_key=True)
      title = db.Column(db.String(80), nullable=False)
      body = db.Column(db.Text, nullable=False)
      pub_date = db.Column(db.DateTime)
  
      categories = db.relationship('Category', secondary=association_table,
                              backref=db.backref('posts', lazy='dynamic'))
  
      ...
  class Category(db.Model):
      id = db.Column(db.Integer, primary_key=True)
      name = db.Column(db.String(50))
      ...
  </code></pre>
  
  <p>I can create new post with next view</p>
  
  <pre><code>def add():
      form = PostForm(request.form)
      if request.method == 'POST' and form.validate():
          post = Post(form.title.data, form.body.data)
          db.session.add(post)
          tags = form.tags.data.split(',')
          for tag in tags:
              category = Category.query.filter_by(name=tag.strip()).first()
              if not category:
                  category = Category(tag.strip())
              post.categories.append(category)
          db.session.commit()
          return redirect(...)
      return render_template(...)
  </code></pre>
  
  <p>That works as it should. But I have a couple of problems with editing of posts. When I change title or body I have to use db.session.merge(post) otherwise it does not want to save changes in database. But in all tutorials there are no that merge method.
  Second problem is that I can not update tags of the post. I can create a new tag and add it to some post. But if I try to add existing tag to any post I have an error. </p>
  
  <pre><code>AssertionError: A conflicting state is already present in the identity map for key (&lt;class 'db.models.Category'&gt;, (1,))
  </code></pre>
  
  <p>my view looks like</p>
  
  <pre><code>def edit(post_id):
      post = Post.query.get(post_id)
      form = PostForm(request.form, post)
      if request.method == 'POST' and form.validate():
  
          ...
  
          tags = form.tags.data.split(',')
          for tag in tags:
              category = Category.query.filter_by(name=tag.strip()).first()
              if not category:
                  category = Category(tag.strip())
              db.session.remove()
              post.categories.append(category)
          form.populate_obj(post)
          db.session.merge(post)
          db.session.commit()
          return redirect(...)
      else:
          ...
  
      return render_template(...)
  </code></pre>
  
  <p>Also if I do not use db.session.remove() I will get another error</p>
  
  <pre><code>InvalidRequestError: Object '&lt;Category at 0x7f9de40c0d90&gt;' is already attached to session '6' (this is '1')
  </code></pre>
  
  <p>Where am I wrong? Thanks for any help!</p>
  
  <p>One update. Just for tests. If I iterate list of tags from one post I can remove those tags and append it back. </p>
  
  <pre><code>tags = list(post.categories)
  for tag in tags:
      post.categories.remove(tag)
  
  for tag in tags:
      post.categories.append(tag)    
  </code></pre>
  
  <p>But if I remove tags then get tag from db and try to append - got an error</p>
  
  <pre><code>tags = list(post.categories)
  for tag in tags:
      post.categories.remove(tag)
  
  for tag in tags:
      category = Category.query.filter_by(name=tag.name).first()
      post.categories.append(tag) 
  
  
  AssertionError: A conflicting state is already present in the identity map for key (&lt;class 'db.models.Category'&gt;, (1,)) 
  </code></pre>
  
  <p>I am confused</p>