kmg92
kmg92

Reputation: 31

Flask-SQLAlchemy wont create tables and Foreign Key

I have a model that wont create the table in the database as shown below

class Person(db.Model):

__tablename__ = 'persons'

id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(20))
pets = db.relationship('Pet', backref='person')

class Pet(db.Model):

__tablename__ = 'pets'

id = db.Column(db.Integer, primary_key=True)
name=db.Column(db.String(20))
owner_id = db.Column(db.Integer, db.ForeignKey('person.id'),nullable=False)

Might the issue be because the class name and the table name do not match since using the command

db.create_all()

throws an error??

Upvotes: 0

Views: 584

Answers (1)

Moses N. Njenga
Moses N. Njenga

Reputation: 771

Change this

owner_id = db.Column(db.Integer, db.ForeignKey('person.id'),nullable=False)

to

owner_id = db.Column(db.Integer, db.ForeignKey('persons.id'),nullable=False)

since your table is persons

And give this relationship a different name since you already have a table called pets

pets = db.relationship('Pet', backref='person')

you could for example do this

persons_pets = db.relationship('Pet', backref='person')

Upvotes: 1

Related Questions