IT/파이썬
sqlalchemy 에러 : Parent instance <Comment at 0x25c4fc08340> is not bound to a Session; lazy load operation of attribute 'answer' cannot proceed
thesse
2021. 5. 31. 15:50
300x250
반응형
@bp.route('/delete/answer/<int:comment_id>')
@login_required
def delete_answer(comment_id):
comment = Comment.query.get_or_404(comment_id)
db.session.delete(comment)
db.session.commit()
return redirect(url_for('question.detail', question_id=comment.answer.question_id))
위와 같이 comment_id를 통해 comment를 db에서 삭제하는 함수를 만들었다,
그런데 실행해보면 db에서 데이터는 사라지는데 페이지가 제대로 로드되지 않고 에러를 띄운다.
sqlalchemy.orm.exc.DetachedInstanceErrorsqlalchemy.orm.exc.DetachedInstanceError: Parent instance is not bound to a Session; lazy load operation of attribute 'answer' cannot proceed (Background on this error at: http://sqlalche.me/e/14/bhk3) |
db 설정이 문제인가 싶어 모델 쪽을 살펴봤지만...
문제는 코드에 있었다.
@bp.route('/delete/answer/<int:comment_id>')
@login_required
def delete_answer(comment_id):
#코멘트 객체 가져옴
comment = Comment.query.get_or_404(comment_id)
# 코멘트 객체를 삭제했으므로 이제 comment는 존재하지 않음
db.session.delete(comment)
db.session.commit()
# 그런데 여기서 comment.answer.question_id를 요구해버림
return redirect(url_for('question.detail', question_id=comment.answer.question_id))
내손으로 comment를 제거하고 커밋까지 때려놓고
comment에서 answer.question_id를 가져오라고 해서 에러가 난 것이었다....
@bp.route('/delete/answer/<int:comment_id>')
@login_required
def delete_answer(comment_id):
comment = Comment.query.get_or_404(comment_id)
question_id = comment.answer.question_id # 여기에 저장해두기
db.session.delete(comment)
db.session.commit()
return redirect(url_for('question.detail', question_id=question_id))
comment를 삭제하기 전에 question_id를 변수로 따로 받아두고 얘를 가져다쓰면 해결
300x250
반응형