首页 > 解决方案 > Python SQLAlchemy 和 SQLite - 外键

问题描述

我完全是一个新手,刚刚开始学习所有这些东西。做一个测试应用程序。

有以下型号:

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(80), unique=True, nullable=False)
    body = db.Column(db.String(3000), nullable=False)

    def __str__(self):
        return '<User %r>' % self.username


class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    body = db.Column(db.String(3000), nullable=False)
    post_id = db.Column(
        db.Integer,
        db.ForeignKey('post.id'),
        nullable=False,
        index=True
    )
    post = db.relationship(Post, foreign_keys=[post_id, ])

Post 表只有一条 ID=1 的记录。但是当我尝试使用 post_is = 10 添加评论时,它起作用了!它实际上插入了一条忽略外键约束的注释!我尝试使用 INSERT 语句对 SQLite 的 DB Browser 执行相同的操作:

insert into comment values (10, 'dfdfdf', 10)

它返回一个外键约束错误。我究竟做错了什么?

这就是我添加评论的方式

@app.route('/add_comment', methods=['POST'])
def add_comment():
    from models import Post, Comment
    from forms import CommentForm

    form = CommentForm(request.form)

    if form.validate():
        comment = Comment(**form.data)
        db.session.add(comment)
        db.session.commit()

        flash('The comment has been added')

    else:
        flash('Form is not valid! Post was not created.')
        flash(str(form.errors))
        comment = False

    return render_template('add_comment.txt', comment=comment)

标签: pythonsqlitesqlalchemy

解决方案


推荐阅读