Minimal example:
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
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. 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). It worked as expected and both the note
and patient
tables were created.
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.
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. It's saying that it can't create the notes
table because there's no such foreign key as patient.id
. This is probably throwing you off because you know you are defining a patient.id
key in models.py
. 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). 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.
Go check your Postgres DB and take a look at the patient
table. Does it actually have an id
column that is properly defined as a primary key?
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.
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.