簡體   English   中英

Flask-SQLAlchemy 'NoForeignKeysError'

[英]Flask-SQLAlchemy 'NoForeignKeysError'

我正在開發 Flask 應用程序,使用 Flask-SQLAlchemy 擴展進行數據庫交互。 由於我在同一個數據庫上編寫了多個應用程序,因此我遇到了 SQLite 的並發問題,我想改用 PostgreSQL。 我可以毫無問題地在新數據庫上創建表,並且 pgAdmin 顯示表和列。

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

但是當涉及到添加用戶時,我現在收到一個錯誤: 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()

完整的錯誤信息:

""" 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. """

我無法弄清楚導致錯誤的原因。 我的模型缺少什么?

# 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)

解決了

你的代碼對我有用。 也許您需要重新創建表或類似的東西。 為了確保我們有相同的代碼:我已經測試了以下代碼:

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)

路線中:

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

print(user)

我終於解決了這個問題,這不是我要找的地方。 由於在初始化應用程序期間導入了錯誤的模型文件,我收到了 NoForeignKeysError。 我導入的一個模塊調用了錯誤/舊版本的模型。 我猜這會導致實際模型中的表關系中斷。

當我逐步完成 create_test_user() 時,我注意到錯誤實際上發生在類創建過程中,甚至在它到達 db.session.add 之前,即使沒有數據庫,我也復制了錯誤。 我瀏覽了所有調用模型的模塊並發現了錯誤的模型導入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM