title: Sqlalchemy duplicate entry when creating entries dynamically
body: <p>In my application, I am using SQLAlchemy (via MySQL) with Flask, and in my current situation I need to create entries dynamically.  For example, while creating an instance from table A, my script will see that we need to create a related entry B, so after creating B, it will attempt to assign B to one of the relationship attributes of the instance for A.</p>
  
  <p>Here are some example models:
  </p>
  
  <pre><code>a_b = db.Table('a_b',
                 db.Column('a_id', db.Integer,
                           db.ForeignKey('a.id',
                                         onupdate="CASCADE",
                                         ondelete="CASCADE"),
                           primary_key=True),
                 db.Column('b_id', db.Integer,
                           db.ForeignKey('b.id',
                                         onupdate="CASCADE",
                                         ondelete="CASCADE"),
                           primary_key=True))
  
  class ModelA(db.Model):
      __tablename__ = 'a'
  
      id = db.Column(db.Integer, primary_key=True)
      name = db.Column(db.String(100), nullable=False)
  
      model_bs = db.relationship('ModelB', secondary=a_b,
                                 back_populates='model_as')
  
  class ModelB(db.Model):
      __tablename__ = 'b'
  
      id = db.Column(db.Integer, primary_key=True)
      name = db.Column(db.String(100), nullable=False)
  
      model_as = db.relationship('ModelA', secondary=a_b,
                                 back_populates='model_bs')
  </code></pre>
  
  <p>The problem I'm running into is an SQL duplicate entry exception, after running something like this:
  </p>
  
  <pre><code>from base import db
  from base.database.models.models import ModelA, ModelB
  
  
  def creation_test():
      with db.session.no_autoflush:
          # Start creating A
          a = ModelA()
          a.name = 'A Example'
  
          # See that we need B, so create B
          b = ModelB()
          b.name = 'B Example'
          b.model_as = []
          db.session.add(b)
          db.session.flush((b,))
  
          # Use B in the relationship from A
          a.model_bs = [b]
          db.session.add(a)
          db.session.flush((a,))
  
      db.session.commit()
  
  creation_test()
  </code></pre>
  
  <p>It will spit out an exception like:</p>
  
  <pre><code>sqlalchemy.exc.IntegrityError: (_mysql_exceptions.IntegrityError) (1062, "Duplicate entry '1-1' for key 'PRIMARY'") [SQL: u'INSERT INTO a_b (a_id, b_id) VALUES (%s, %s)'] [parameters: (1L, 1L)]
  </code></pre>
  
  <p>Is there something wrong with how the entries are being added to the session and/or how they are being flushed?  Is it even possible to instantiate entries like this?</p>
  
  <p>I appreciate any feedback.</p>