在SQLAlchemy中创建外键失败

2024-07-02 10:56:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望每个用户都有一个名为allocatedstorageavailablestorage的值。这两个值存储在另一个表中。但是,当我创建以下数据库时,它会显示以下错误。我做错什么了?谢谢你的帮助。在

class User(UserMixin, db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(15), unique=True)
    email = db.Column(db.String(50), unique=True)
    password = db.Column(db.String(80))
    role= db.Column(db.String(20));
    usersessiontoken = db.Column(db.String(500), unique=True)
    hasstorage = db.Column(db.Integer, db.ForeignKey('storageinformation.allocatedstorage'))
    hasavailablestorage = db.Column(db.Integer, db.ForeignKey('storageinformation.availablestorage'))

    storageinformation = db.relationship('StorageInformation', backref='user')

class StorageInformation(UserMixin, db.Model):
    __tablename__ = 'storageinformation'
    id = db.Column(db.Integer, primary_key=True)
    allocatedstorage = db.Column(db.Integer)
    availablestorage = db.Column(db.Integer)

错误:

^{pr2}$

Tags: truedbstringmodel错误columnintegerclass
1条回答
网友
1楼 · 发布于 2024-07-02 10:56:20
  • 在我的例子中,实际的原因没有显示在migration命令的输出中
  • 只有在数据库控制台中运行相同的命令,我才能发现问题

命令是 ALTER TABLE assignment ADD FOREIGN KEY(session_id) REFERENCES battery (session_id)

实际问题 Create table 'db_name/#sql-5f9_11e' with foreign key constraint failed. There is no index in the referenced table where the referenced columns appear as the first columns. Cannot add foreign key constraint

{a1}

MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order.

InnoDB permits a foreign key to reference any index column or group of columns. However, in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order.

相关问题 更多 >