简体   繁体   English

在外键约束中引用的烧瓶SQLAlchemy列“ id”不存在

[英]Flask SQLAlchemy column “id” referenced in foreign key constraint does not exist

Minimal example: 最小示例:

models.py models.py

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Patient(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    notes = db.relationship("Note", backref=db.backref("patient", lazy=True))

class Note(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    patient_id = db.Column(db.Integer, db.ForeignKey("patient.id"), nullable=False)

app.py app.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.secret_key = "super secret"

POSTGRES = {
    "user": "postgres",
    "pw": "password",
    "db": "test_db",
    "host": "localhost",
    "port": "5432",
}
app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://%(user)s:%(pw)s@%(host)s:%(port)s/%(db)s" % POSTGRES
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["DEBUG"] = True

from models import db
with app.app_context():
    db.init_app(app)

run.py 运行

from app import app, db

if __name__ == "__main__":
    with app.app_context():
        db.create_all()
    app.run()

However, I get the following error: 但是,出现以下错误:

sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) column "id" referenced in foreign key constraint does not exist
 [SQL: '\nCREATE TABLE note (\n\tid SERIAL NOT NULL, \n\tpatient_id INTEGER NOT NULL, \n\tPRIMARY KEY (id), \n\tFOREIGN KEY(patient_id) REFERENCES patient (id)\n)\n\n'] (Background on this error at: http://sqlalche.me/e/f405)

It seems to work when I define the table with the foreign key in a psql console. 当我在psql控制台中使用外键定义表时,它似乎起作用。 What's going wrong? 怎么了

I tried your sample code (I had to add the app initialisation to app.py so your code would run as-is). 我尝试了您的示例代码(我必须将应用程序初始化添加到app.py中,以便您的代码可以按原样运行)。 It worked as expected and both the note and patient tables were created. 它按预期方式工作,并且创建了notepatient表格。

This tells me that your issue is environmental. 这告诉我您的问题是环境问题。 I'm willing to bet that if you created a brand new test database in your Postgres instance and ran your example code it would work for you too. 我愿意打赌,如果您在Postgres实例中创建了一个全新的测试数据库并运行了示例代码,那么它也将为您服务。

So let's focus on the state of the database you're connecting to. 因此,让我们专注于您要连接的数据库的状态。

The ProgrammingError exception you're getting shows an error coming from Postgres itself. 您收到的ProgrammingError异常显示了来自Postgres本身的错误。 It's saying that it can't create the notes table because there's no such foreign key as patient.id . 就是说它无法创建notes表,因为没有诸如patient.id这样的外键。 This is probably throwing you off because you know you are defining a patient.id key in models.py . 这可能会让您失望,因为您知道自己在models.py 定义了patient.id键。 Unfortunately I don't have enough information from what you've posted to give you a definitive answer, but my guess is this: 不幸的是,我没有足够的信息来提供确切的答案,但是我的猜测是:

The patient table in Postgres may have already been created from a previous run, but with a different schema (eg maybe it was first defined without an id column). Postgres中的patient表可能已经从先前的运行中创建,但是具有不同的模式(例如,它最初是在没有id列的情况下定义的)。 the create_all() function will create tables that don't exist in the target database, but will not update existing tables with a modified schema. create_all()函数将创建目标数据库中不存在的表,但不会使用已修改的架构来更新现有表。

Go check your Postgres DB and take a look at the patient table. 去检查您的Postgres DB并查看patient表。 Does it actually have an id column that is properly defined as a primary key? 它实际上是否具有正确定义为主键的id列?

If there's no data in these tables that you need, try dropping them and running your app again. 如果这些表中没有您需要的数据,请尝试删除它们并再次运行您的应用程序。 My guess is that it will create both tables correctly and throw no errors. 我的猜测是它将正确创建两个表,并且不会引发任何错误。

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

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