1

我有一个工作博客系统。我想将它添加到评论系统。我使用带有 id、title 和 body 的 post 模型完成了迁移。

现在我添加评论并创建名为 Comment 的新模型。当我运行迁移时:

信息 [alembic.runtime.migration] 上下文 impl MySQLImpl。

INFO [alembic.runtime.migration] 将假定非事务性 DDL。

INFO [alembic.env] 未检测到架构更改。

from run import db

class Post(db.Model):
    __tablename__ = 'blog.post'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String, nullable=False)
    body = db.Column(db.Text, nullable=False)

    comments = db.relationship('Comment', backref='blog.post')


from run import db


class Comment(db.Model):   
    __tablename__ = 'blog.comment'
    id = db.Column(db.Integer, primary_key=True)
    body = db.Column(db.Text, nullable=False)

    post_id = db.Column(db.Integer, db.ForeignKey('blog.post.id'), nullable=False)

我不知道我的代码有什么问题。我从文档中获取关系并对其进行编辑。db 之前没有任何评论表。

编辑1:我在运行中调用评论如下: from model.comment import Comment

之后我可以创建迁移但迁移出现如下错误:

sqlalchemy.exc.InternalError: (pymysql.err.InternalError) (1005, 'Can\'t create table blog_db. blog.comment(errno: 150 "Foreign key constraint is wrongly forms")') [SQL: '\nCREATE TABLE blog.comment(\n\ tid INTEGER NOT NULL AUTO_INCREMENT, \n\tname VARCHAR(255) NOT NULL, \n\tbody TEXT NOT NULL, \n\tcreated DATETIME DEFAULT now(), \n\tstatus INTEGER NOT NULL, \n\tpost_id INTEGER NOT NULL , \n\tPRIMARY KEY (id), \n\tFOREIGN KEY(post_id) REFERENCES blog.post (id)\n)\n\n'] (此错误的背景:http ://sqlalche.me/e /2j85 )

4

1 回答 1

1

发生错误Foreign key constraint is incorrectly formed是因为主键和外键具有不同的类型。

Post模型中,您将id列定义为:

id = db.Column(db.Integer, primary_key=True)

但是post_id您在模型中添加的外键Comment定义不同:

post_id = db.Column(db.Integer, db.ForeignKey('blog.post.id'), nullable=False)

我认为如果您nullable从外键中删除该子句,您将接受迁移。

于 2018-02-19T06:49:48.327 回答