Chase Quinn
Chase Quinn

Reputation: 91

sql-alchemy sqlite database problems, it is not allow me to create foreign keys

here is my code:

class usersTable(db.Model):
    userid = db.Column(db.Integer, primary_key=True)
    fname = db.Column(db.String, nullable=False)
    lname = db.Column(db.String, nullable=False)
    email = db.Column(db.LargeBinary, unique=True, nullable=False)
    username = db.Column(db.LargeBinary, unique=True, nullable=False)
    password = db.Column(db.LargeBinary, nullable=False)
    joined = db.Column(db.Date, nullable=False)
    subuser = db.relationship('subuserTable', backref='userid')

class subuserTable(db.Model):
    userid = db.Column(db.Integer, db.ForeignKey('usersTable.userid'))
    subid = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.LargeBinary, unique=True, nullable=False)
    password = db.Column(db.LargeBinary, nullable=False)
    fname = db.Column(db.String, nullable=False)
    lname = db.Column(db.String, nullable=False)
    admin = db.Column(db.Boolean, default=False)

The problem is that whenever i try to run:

db.create_all()

I run into this error:

sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'subuser_table.userid' could not find table 'usersTable' with which to generate a foreign key to target column 'userid'

I know that there is a usersTable table, and also the userid column is there, so why is it giving me this much grief?

Upvotes: 0

Views: 137

Answers (1)

ParthS007
ParthS007

Reputation: 2691

Change this:

userid = db.Column(db.Integer, db.ForeignKey('usersTable.userid'))

to

userid = db.Column(db.Integer, db.ForeignKey('users_table.userid'))

From Flask SQLAlchemy docs:

Some parts that are required in SQLAlchemy are optional in Flask-SQLAlchemy. For instance, the table name is automatically set for you unless overridden. It’s derived from the class name converted to lowercase and with “CamelCase” converted to “camel_case”. To override the table name, set the tablename class attribute.

Upvotes: 1

Related Questions