'How to map table relationships with flask-sqlalchemy, before tables exist?

I have a problem creating relationships between my tables in flask-sqlalchemy. I have a table with project overview, and from there on out I want to dynamically create new experiment tables with a relationship to my project overview. However, when I try to define the relationship, sqlalchemy throws the following error:

sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Projects->projects, expression 'Experiment_Overview' failed to locate a name ('Experiment_Overview'). If this is a c
lass name, consider adding this relationship() to the <class 'app.Projects'> class after both dependent classes have been defined.

This seems to be the case because the class Experiment_Overview(db.Model) does not exist yet, which is correct since it will be dynamically generated later on through user input. How can I mitigate this error?

import os
from flask import Flask, render_template, redirect, request, url_for
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

app = Flask(__name__)
Bootstrap(app)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///DATA/DB.db"
db = SQLAlchemy(app)


def TableCreator(tablename):
  class Experiment_Overview(db.Model):
    __tablename__ = tablename
    creation_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    experiment_name = db.Column(db.String(30), unique=False, nullable=False, primary_key=True)
    projectname = db.Column(db.String(150), db.ForeignKey('projects.projectname'), nullable=False, unique=True)
  return MyTable

class Projects(db.Model):
    projectname = db.Column(db.String(150), unique=True, nullable=False, primary_key=True)
    creation_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    experiments = db.relationship('Experiment_Overview', backref="experiments", lazy=True, uselist=False)

    def __init__(self, owner, projectname, status, created_at):
        self.owner=owner
        self.projectname=projectname
        self.status=status
        self.created_at=created_at

db.create_all()


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source