SQLAlchemy InvalidRequestError: failed to locate name happens only on gunicorn <p>Okay, so I have the following. In <code>user/models.py</code>:</p> <pre><code>class User(UserMixin, SurrogatePK, Model): __tablename__ = 'users' id = Column(db.Integer, primary_key=True, index=True) username = Column(db.String(80), unique=True, nullable=False) email = Column(db.String(80), unique=False, nullable=False) password = Column(db.String(128), nullable=True) departments = relationship("Department",secondary="user_department_relationship_table", back_populates="users") </code></pre> <p>and in <code>department/models.py</code>:</p> <pre><code>user_department_relationship_table=db.Table('user_department_relationship_table', db.Column('department_id', db.Integer,db.ForeignKey('departments.id'), nullable=False), db.Column('user_id',db.Integer,db.ForeignKey('users.id'),nullable=False), db.PrimaryKeyConstraint('department_id', 'user_id') ) class Department(SurrogatePK, Model): __tablename__ = 'departments' id = Column(db.Integer, primary_key=True, index=True) name = Column(db.String(80), unique=True, nullable=False) short_name = Column(db.String(80), unique=True, nullable=False) users = relationship("User", secondary=user_department_relationship_table,back_populates="departments") </code></pre> <p>Using the flask development server locally this works totally fine. However, once I deploy to the standard python buildpack on heroku, the <code>cpt/app.py</code> loads both modules to register their blueprints:</p> <pre><code>from cpt import ( public, user, department ) ... def register_blueprints(app): app.register_blueprint(public.views.blueprint) app.register_blueprint(user.views.blueprint) app.register_blueprint(department.views.blueprint) return None </code></pre> <p>and eventually errors out with the following:</p> <blockquote> <p>sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|User|users, expression 'user_department_relationship_table' failed to locate a name ("name 'user_department_relationship_table' 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>I'd like to know if there's a better way to organize these parts to avoid this error obviously, but I'm more curious why this organization works fine on the development server but blows up something fierce on gunicorn/heroku.</p>