简体   繁体   English

Flask-SQLAlchemy 'NoForeignKeysError'

[英]Flask-SQLAlchemy 'NoForeignKeysError'

I am working on a Flask app, using Flask-SQLAlchemy extension for database interactions.我正在开发 Flask 应用程序,使用 Flask-SQLAlchemy 扩展进行数据库交互。 Since I have multiple apps writing on the same DB, I was getting concurrency issues with SQLite and I wanted to switch to PostgreSQL instead.由于我在同一个数据库上编写了多个应用程序,因此我遇到了 SQLite 的并发问题,我想改用 PostgreSQL。 I am able to create the tables on new database without a problem and pgAdmin displays the tables and columns.我可以毫无问题地在新数据库上创建表,并且 pgAdmin 显示表和列。

# working
def createTables():
    with app.app_context():
        from models import User, Invoice
        db.create_all()

But when it comes to adding a user, I am now getting an error: sqlalchemy.exc.NoForeignKeysError Although, I think, I declared one-to-many relationship in my models, based on the documentation , I get an error states that "there are no foreign keys linking these tables."但是当涉及到添加用户时,我现在收到一个错误: sqlalchemy.exc.NoForeignKeysError尽管我认为我在我的模型中声明了一对多关系,但根据文档,我收到一个错误状态“没有链接这些表的外键。”

# not working
def create_test_user():
    with app.app_context():
    user = User(
        username="Bob",
        email="bob@email.com",
        password="test"
        )
    db.session.add(user) 
    db.session.commit()

The full error message:完整的错误信息:

""" NoForeignKeysError: Could not determine join condition between parent/child tables on relationship User.invoices 
- there are no foreign keys linking these tables.  
Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression. """

I can't figure out what causes the error.我无法弄清楚导致错误的原因。 What is missing with my models?我的模型缺少什么?

# models.py
class User(db.Model):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password = db.Column(db.String(60), nullable=False)
    invoices = db.relationship('Invoice', backref='user', lazy=True)

class Invoice(db.Model):
    __tablename__ = "invoice"
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    amount = db.Column(db.Integer, nullable=False)

Solved解决了

Your code works for me.你的代码对我有用。 Maybe you need to re-create your tables or something similar.也许您需要重新创建表或类似的东西。 To be sure that we have the identical code: I have tested the following code:为了确保我们有相同的代码:我已经测试了以下代码:

class User(db.Model):
  __tablename__ = "user"
  id = db.Column(db.Integer, primary_key=True)
  username = db.Column(db.String(20), unique=True, nullable=False)
  email = db.Column(db.String(120), unique=True, nullable=False)
  password = db.Column(db.String(60), nullable=False)
  invoices = db.relationship('Invoice', backref='user', lazy=True)

class Invoice(db.Model):
  __tablename__ = "invoice"
  id = db.Column(db.Integer, primary_key=True)
  user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
  amount = db.Column(db.Integer, nullable=False)

In the route:路线中:

user = User(
    username="Bob",
    email="bob@email.com",
    password="test"
    )
db.session.add(user) 
db.session.commit()

print(user)

I finally solved the problem and it was not where I was looking for.我终于解决了这个问题,这不是我要找的地方。 I was getting NoForeignKeysError due to importing a wrong model file during initializing the app.由于在初始化应用程序期间导入了错误的模型文件,我收到了 NoForeignKeysError。 One of my imported modules was calling a wrong/old version of the model.我导入的一个模块调用了错误/旧版本的模型。 It was causing the table relationship in the actual model to break I guess.我猜这会导致实际模型中的表关系中断。

When I went through step by step create_test_user() I noticed that the error occurs actually during the class creation, before even it hits to db.session.add and I replicated the error even without a DB.当我逐步完成 create_test_user() 时,我注意到错误实际上发生在类创建过程中,甚至在它到达 db.session.add 之前,即使没有数据库,我也复制了错误。 I went through all my modules that are calling the models and caught wrong model import.我浏览了所有调用模型的模块并发现了错误的模型导入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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