我正在尝试在User_Info表和其余表之间建立外键(一对多关系),但这给了我这个错误:
sqlalchemy.exc.ProgrammingError:(psycopg2.errors.UndefinedTable) 关系“ user_info”不存在第1行:INSERT INTO user_info (用户名,名字,姓氏,性别... ^
[SQL:INSERT INTO user_info(用户名,名字,姓氏,性别, date_of_birth,profile_img_url)VALUES(%(用户名)s,%(first_name)s, %(last_name)s,%(gender)s,%(date_of_birth)s,%(profile_img_url)s) RETURNING user_info.id] [参数:{'username':'gohammedhl', 'first_name':'Ameer','last_name':'Farqad','gender':'1', 'date_of_birth':'2019-09-25','profile_img_url':'bla bla'}]] (此错误的背景位于:http://sqlalche.me/e/f405)
这是我的桌子:
class User_Info(UserMixin, db.Model):
__tablename__ = "user_info"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), nullable=False, unique=True)
first_name = db.Column(db.String(30), nullable=False)
last_name = db.Column(db.String(30), nullable=False)
gender = db.Column(db.String(2), nullable=False)
date_of_birth = db.Column(db.DATE, nullable=False)
profile_img_url = db.Column(db.String, nullable=True)
post = db.relationship("Posts", backref="post_author", lazy=True)
comment = db.relationship("Comments", backref="comment_author", lazy=True)
phone_number = db.relationship("User_Auth", backref="ph_no_owner", lazy=True)
class User_Auth(UserMixin, db.Model):
__tablename__ = "user_auth"
id = db.Column(db.Integer, primary_key=True)
phone_no = db.Column(db.String(100), nullable=False, unique=True)
password_hash = db.Column(db.String(300), nullable=False)
ph_no_owner_id = db.Column(db.Integer, db.ForeignKey("user_info.id"))
class Posts(db.Model):
__tablename__ = "posts"
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(150), nullable=False)
img_url = db.Column(db.String(400), nullable=True)
post_date = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
post_author_id = db.Column(db.Integer, db.ForeignKey("user_info.id"))
class Comments(db.Model):
__tablename__ = "comments"
id = db.Column(db.Integer, primary_key=True)
comment = db.Column(db.String(150), nullable=False)
comment_date = db.Column(db.DateTime, default=datetime.utcnow)
comment_author_id = db.Column(db.Integer, db.ForeignKey("user_info.id"))
有什么想法吗? 预先感谢!
答案 0 :(得分:0)
我解决了!
它缺少:
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = ("postgresql://postgres:PasswordHere@localhost/dbName")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
并且:
with app.app_context():
db.create_all()
尽管此代码是在用于创建内容的单独文件中创建的,但是直到我将其放入上表的同一文件中后,它才能正常工作!