I'm completely a newbie, just started learning all this stuff. Doing a test app.
Have the following models:
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, ])
The table Post has only one record with ID=1. But when I try to add a comment with post_is = 10, it works! And it actually inserts a comment ignoring the foreign key constraint! I tried to do the same with DB Browser for SQLite using INSERT statement:
insert into comment values (10, 'dfdfdf', 10)
and it returns a foreign key constraint error. What am I doing wrong?
this is how I add a comment
@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)