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
반응형
'IT > 파이썬' 카테고리의 다른 글
[점프투플라스크] 이미 추천했습니다 띄우기 (0) | 2021.06.01 |
---|---|
[플라스크] 다대다 관계 모델 설정 (SQLAlchemy) (0) | 2021.05.31 |
flask db migrate시 에러 ValueError: not enough values to unpack (expected 2, got 1) (0) | 2021.05.31 |
[플라스크] ModuleNotFoundError: No module named 'flask_wtf' 에러 (0) | 2021.05.28 |
파이썬 데코레이터 (1) | 2021.05.27 |