简体   繁体   中英

Flask-SQLAlchemy: One-To-Many between separate moduls (NoReferencedTableError)

I have two model classes in separate files, created a One-To-Many relationship between them.

user.py:

class User(db.Model):
    __tablename__ = 'users'
    id =        db.Column(db.Integer,           primary_key=True)
    email =     db.Column(db.String(100),       index=True, unique=True, nullable=False)
    password =  db.Column(db.String(128),       nullable=False)
    projects =  db.relationship('Project', backref='owner', lazy='dynamic')

project.py:

class Project(db.Model):
    __tablename__ = 'projects'
    id          =   db.Column(db.Integer,       primary_key=True)
    name        =   db.Column(db.String(100),   index=True, unique=True, nullable=False)
    owner_id    =   db.Column(db.Integer, db.ForeignKey('User.id'))

This is how I create my app:

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = DB_URL
db = SQLAlchemy(app)

@app.before_first_request
def create_tables():
    db.create_all()

app.run(debug=True)

However when I create a request I get the following error:

sqlalchemy.exc.NoReferencedTableError: 
Foreign key associated with column 'projects.owner_id' could not find 
table 'User' with which to generate a foreign key to target column 'id'

I understand this is a duplicate of this question asked before, however I tried that and did not work:

@app.before_first_request
def create_tables():
    from projectx.models.auth.user import User
    from projectx.models.private_data.project import Project
    db.create_all()

I also tried giving the same __table_args__ = {"schema": "testdb"} args to both models (I manually created the db with this name) and refer to db.ForeignKey('testdb.User.id) to no avail, the error is the same.

What am I missing here?

It seems I misunderstood some concepts about how this relationship abstraction works. The foreign key reference is to the tablename and not the class name naturally.

I should have written db.ForeignKey('users.id') .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM