我编写了以下代码:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(255), nullable=True)
last_name = db.Column(db.String(255), nullable=True)
email = db.Column(db.String(255), unique=True, nullable=False)
password_expires_at = db.Column(db.DateTime, nullable=False)
active = db.Column(db.Boolean, nullable=False)
created_at = db.Column(db.DateTime, nullable=False,
default=datetime.utcnow)
updated_at = db.Column(db.DateTime, nullable=False,
default=datetime.utcnow)
session_id = db.Column(db.Integer, db.ForeignKey('session.id'),
nullable=False)
class Session(db.Model):
id = db.Column(db.String(255), primary_key=True)
ip = db.Column(db.String(255), unique=True, nullable=False)
user = db.relationship('User', backref='session')
db.create_all()
运行Flask时出现以下错误:
sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (1005, 'Can\'t create table `bugbot`.`user` (errno: 150 "Foreign key constraint is incorrectly formed")')
[SQL:
CREATE TABLE user (
id INTEGER NOT NULL AUTO_INCREMENT,
first_name VARCHAR(255),
last_name VARCHAR(255),
email VARCHAR(255) NOT NULL,
password_expires_at DATETIME NOT NULL,
active BOOL NOT NULL,
created_at DATETIME NOT NULL,
updated_at DATETIME NOT NULL,
session_id INTEGER NOT NULL,
PRIMARY KEY (id),
UNIQUE (email),
CHECK (active IN (0, 1)),
FOREIGN KEY(session_id) REFERENCES session (id)
)
]
我遵循了获得此代码的教程,所以我不知道自己在做什么错。有人可以帮我吗?
答案 0 :(得分:3)
您要在(User.session_id
上施加约束的列的类型为Integer
,而它所引用的列(Session.id
)的类型为String
!这就是为什么它会失败,使两种类型都兼容,然后再次运行,它应该可以工作。