title: How to prevent this circular reference in Flask/SQLAlchemy Models?
body: <p>I have the following four model classes in my Flask/SQLAlchemy application (a fifth class <code>MyClassA</code> is not shown here but is reference):</p>
  
  <pre><code>class MyClassF(db.Model):
      valid_fs = ['F1', 'F2']
      f_id = db.Column(db.Integer, nullable=False, primary_key=True)
      name = db.Column(db.Enum(*valid_fs, name='f_enum'), default='F1', nullable=False)
  
  class MyClassD(db.Model):
      d_id = db.Column(db.Integer, nullable=False, primary_key=True)
      name = db.Column(db.String(128))
      v_collection = db.relationship('MyClassV', lazy='dynamic', backref=db.backref('d'), cascade='all, delete-orphan')
  
  class MyClassV(db.Model):
      v_id = db.Column(db.Integer, nullable=False, primary_key=True)
      d_id = db.Column(db.Integer, db.ForeignKey(MyClassD.d_id), nullable=False)
      c_collection = db.relationship('MyClassC', lazy='dynamic', backref=db.backref('v'), cascade='all, delete-orphan')
      a_collection = db.relationship('MyClassA', lazy='dynamic', backref=db.backref('v'), cascade='all, delete-orphan')
  
  class MyClassC(db.Model):
      c_id = db.Column(db.Integer, nullable=False, primary_key=True)
      v_id = db.Column(db.Integer, db.ForeignKey(MyClassV.v_id), nullable=False)
      f_id = db.Column(
          db.Integer,
          db.ForeignKey(MyClassF.f_id),
          nullable=False,
          #default=MyClassF.query.filter(MyClassF.name == "F1").one().f_id
      )
  </code></pre>
  
  <p>Creating this schema using the <a href="https://flask-migrate.readthedocs.io/en/latest/" rel="nofollow noreferrer">Flask-Migrate</a> command <code>db init</code>, <code>db migrate</code> and <code>db upgrade</code> works just fine.</p>
  
  <p>However, when I un-comment the line the definition of <code>MyClassC.f_id</code> and try it again (after removing the <code>migrations</code> directory), I get the following circular dependency error:</p>
  
  <blockquote>
    <p>sqlalchemy.exc.InvalidRequestError: When initializing mapper
    Mapper|MyClassV|my_classV, expression 'MyClassC' failed to locate a
    name ("name 'MyClassC' is not defined"). If this is a class name,
    consider adding this relationship() to the 
    class after both dependent classes have been defined.</p>
  </blockquote>
  
  <p>All I'm trying to do is ensure that the default value of <code>MyClassC.f_id</code> is set by querying the <code>MyClassF</code> table. This check should occur at insertion time -- not when the database is being created. So I don't understand why I am getting this error now.</p>
  
  <p>How can I use <code>db.relationship()</code> (or any other technique) to get around this circular dependency error while enforcing the database integrity rule I'm trying to implement?</p>