Reputation: 81
I'm trying to make a foreign key (one-to-many relationship) between User_Info table and the rest tables, but it gives me this error:
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "user_info" does not exist LINE 1: INSERT INTO user_info (username, first_name, last_name, gend... ^
[SQL: INSERT INTO user_info (username, first_name, last_name, gender, date_of_birth, profile_img_url) VALUES (%(username)s, %(first_name)s, %(last_name)s, %(gender)s, %(date_of_birth)s, %(profile_img_url)s) RETURNING user_info.id] [parameters: {'username': 'gohammedhl', 'first_name': 'Ameer', 'last_name': 'Farqad', 'gender': '1', 'date_of_birth': '2019-09-25', 'profile_img_url': 'bla bla'}] (Background on this error at: http://sqlalche.me/e/f405)
And here are my tables:
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"))
Any ideas? Thanks in advance!
Upvotes: 3
Views: 3985
Reputation: 81
I solved it!
It was lacking:
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = ("postgresql://postgres:PasswordHere@localhost/dbName")
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
And:
with app.app_context():
db.create_all()
Though this code was in a seperate file created for creating stuff, but it didn't work properly until I put it in the same file of the tables above!
Upvotes: 4