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'))