SQLAlchemy在多对多关系中无法通过外键找到引用表



我已经成功地在数据库中添加了一个多对多关系。然而,当我试图添加另一个时,我遇到了:

sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'user_shiftTemplate.template_id' could not find table 'shifttemplate' with which to generate a foreign key to target column 'id'

我已经在我的两个表之前定义了关联表,我试图创建一个关系:

user_shiftTemplate = db.Table('user_shiftTemplate',
db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
db.Column('template_id', db.Integer, db.ForeignKey('shifttemplate.id'))
)

这里是我实际的两个表,我试图创建的关系(再次,定义后的关联表如上所示)

class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
oauth_id = db.Column(db.String(512), nullable=False, unique=True, default='')
ext_id = db.Column(db.Integer, nullable=False, unique=True)
name = db.Column(db.String(300), nullable=False)
email = db.Column(db.String(256), unique=True, nullable=False)
phone = db.Column(db.Integer, nullable=False)
date_joined = db.Column(db.DateTime, nullable=False, default=getPacificTime)
password = db.Column(db.String(60), nullable=False)
meta = db.Column(db.JSON, nullable=False, default={})
shifts = db.relationship('Shift', secondary=user_shift, backref='employees') 
#^^^^ This is the other many-to-many relationship which actually works ^^^^
shiftTemplates = db.relationship('ShiftTemplate', secondary=user_shiftTemplate, backref='employees')
class ShiftTemplate(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(128), nullable=False)
duration = db.Column(db.Integer, nullable=False)
maxEmployees = db.Column(db.Integer, nullable=False)
minEmployees = db.Column(db.Integer, nullable=False)
startTime = db.Column(db.String(4), nullable=False)

我仔细地确保了我的ShiftTemplate表的格式与我成功创建的另一个多对多关系表的格式相匹配。但是,由于某种原因,某些东西导致SQLAlchemy无法识别我的ShiftTemplate表。还应该注意的是,在关联表定义的db.ForeignKey(' shiftTemplate .id')行中,我尝试了每个大写组合,从shiftTemplate到shiftTemplate再到shiftTemplate,它们都返回相同的错误,所以我怀疑这是原因。

could not find table 'shifttemplate'-最有可能生成的名称(我认为是flask-sqlalchemy)与您使用的名称有点不同,您可以通过__tablename__类变量手动指定tableaem,如下所示:

class Post(Base):
__tablename__ = "post"
...

但回到你的问题-是的,sqlalchemy可能是大小写敏感的,而不是bug:)

我将我的ShiftTemplate数据库表类重命名为"Template"并相应地更新对表名的所有引用。

最新更新