简体   繁体   中英

Flask SQLAlchemy could not find table with which to generate Foreign Key even though table exists

class BigBoxModel(db.Model):
    __tablename__ = "bigbox"
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    name = db.Column(db.String, unique=True, nullable=False)
    vendor_id = db.Column(db.BigInteger, db.ForeignKey("vendors.id"), nullable=False)

I am trying to work with the bigbox table but keep getting the error:

Foreign key associated with column 'bigbox.vendor_id' could not find table 'vendors' with which to generate a foreign key to target column 'id'

The vendors table exists in another file. I cannot import it because that results in circular imports as there are a lot of commonly used libraries present in both files. I have also checked all the table names by running the command:

db.engine.table_names()

And the vendors table does exist but I still keep getting the same error. I am using Flask, SQLalchemy, Postgres.

You could try to use the Class name for foreign key mapping. In your BigBoxModel, you can have something like
vendor_id = db.Column(db.BigInteger, db.ForeignKey(Vendors.id), nullable=False). In this case Vendors is assumed to be the class name.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM