1

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)
Ilja Everilä
  • 50,538
  • 7
  • 126
  • 127
user3751086
  • 229
  • 1
  • 3
  • 9
  • Could you post code, of how do you insert values from the python script? Also, if you check database via DB Browser after inserting data from script, do you actually see that value there (with `post_id = 10`)? – kosist Nov 16 '18 at 09:57
  • @kosist, yes, I can see the comment with post_id=10 in the DB Explorer. I have updated my initial post with the method to add a comment – user3751086 Nov 16 '18 at 10:42
  • See specifically this answer: https://stackoverflow.com/a/7831210/2681632. Your DB explorer most probably sets the required pragma. – Ilja Everilä Nov 16 '18 at 10:57
  • @IljaEverilä I have added the following code as instructed on the page you refer to, but still doesn't help `engine = create_engine(config.SQLALCHEMY_DATABASE_URI) def _fk_pragma_on_connect(dbapi_con, con_record): dbapi_con.execute('pragma foreign_keys=ON') event.listen(engine, 'connect', _fk_pragma_on_connect)` – user3751086 Nov 16 '18 at 13:47
  • You are using Flask-SQLAlchemy, so the engine you create on your own has nothing to do with the `Engine` instance held by the `db` object. You must listen to `connect` on that. If I remember correctly, there's `db.get_engine()` or some such. Alternatively listen globally, as explained in another answer: https://stackoverflow.com/a/15542046/2681632 – Ilja Everilä Nov 16 '18 at 15:26

0 Answers0