1

I have my models set up (or so I thought) that when a post is deleted if the user had commented on it that comment should also delete from the database. But the comments are still present in the database. any idea what am I doing wrong? Thanks in advance

Post and Comment modules:

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.Text, nullable=False)
    date_created = db.Column(db.DateTime(timezone=True), default=func.now())
    author = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False)
    comments = db.relationship('Comment', backref='post', passive_deletes=True)


class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.Text(200), nullable=False)
    date_created = db.Column(db.DateTime(timezone=True), default=func.now())
    author = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False)
    post_id = db.Column(db.Integer, db.ForeignKey('post.id', ondelete='CASCADE'), nullable=False)

delete post route:

@views.route("/delete-post/<id>")
@login_required
def delete_post(id):
    post = Post.query.filter_by(id=id).first()
    if not post:
        flash("Post does not exist", category='error')
    elif current_user.id != post.user.id:
        flash('No permission to delete this post', category='error')
    else:
        db.session.delete(post)
        db.session.commit()
        flash('Post deleted', category='success')
    return redirect(url_for('views.home'))
davidism
  • 121,510
  • 29
  • 395
  • 339
dmtree
  • 29
  • 1
  • 1
    Hey! Could you also share information about the database you are using? Depending on the underlying database, relationships might not be enforced by default (for example sqlite: https://stackoverflow.com/questions/5890250/on-delete-cascade-in-sqlite3) – Alex Feb 24 '23 at 17:33
  • I'm new to this stuff so sorry for my ignorance - I use sqlalchemy and I guess it uses sqlite? And also link you provided, where should I run the - PRAGMA foreign_keys = ON command? Thank you – dmtree Feb 24 '23 at 17:36
  • 1
    No worries! Do you have something like this `app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db"` in your code ? – Alex Feb 24 '23 at 17:41
  • yes I do have that - app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}' – dmtree Feb 24 '23 at 17:47
  • 1
    So that means that you are indeed using sqlite. From what I've read this PRAGMA command needs to be run every time a new connection is made. This question should help you do that: https://stackoverflow.com/questions/2614984/sqlite-sqlalchemy-how-to-enforce-foreign-keys (there is a specific answer pretty recent for Flask/SQLAlchemy) – Alex Feb 24 '23 at 17:51

0 Answers0