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

问题描述 投票:0回答:2

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

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,它们都返回相同的错误,所以我怀疑是原因。

python sqlalchemy foreign-keys many-to-many flask-sqlalchemy
2个回答
1
投票

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

class Post(Base):
    __tablename__ = "post"

    ...

但回到你的问题 - 是的,sqlalchemy 可能区分大小写,并且没有错误:)


-1
投票

我将 ShiftTemplate 数据库表类重命名为“Template”,并相应更新了对表名称的所有引用。我还没有发现为什么会这样。

© www.soinside.com 2019 - 2024. All rights reserved.