我有一张现有的表
class Table1(db.Model):
id = db.Column(db.Integer, primary_key=True)
primary_category_id = db.Column(db.Integer)
def __repr__(self):
return '<Table1 %r>' % (self.id)
已经填充了。现在我想添加一个新表
class Query_Category(db.Model):
category_id = db.Column(db.Integer, primary_key=True)
category_string = db.Column(db.String(1000))
def __repr__(self):
return '<Query_Category %r>' % (self.category_id)
旧表Table1的category_id,现在应该是新表的外键。我正在使用flask-migrate添加Query_Category表,并且工作正常,但如何添加外键约束? 我试着把它添加为
primary_category_id = db.Column(db.Integer, db.ForeignKey('query_category.category_id'))
并运行flask-migrate,但这会导致以下错误
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'Table1.primary_category_id' could not find table 'query_category' with which to generate a foreign key to target column 'category_id'
如何向现有表添加外键约束?
答案 0 :(得分:1)
尝试在模型中添加__tablename__
字段
class Query_Category(Base):
__tablename__ = 'query_category'