코딩 연습/Django
템플릿에서 게시글과 연결된 모든 댓글 가져오기
쵸잇
2018. 11. 23. 11:55
지난 포스트(https://practice-a-lot.tistory.com/42)에서 "related_name" 치트를 활용하는 방법을 보았다.
그에 대한 연장선으로 view에서 comment_list를 만들어줄 필요 없이 템플릿 자체에서 구현하는 방법을 볼 것이다.
먼저 view에서 작성한 comment_list를 삭제한다
1 2 3 4 5 6 | def detail(request, article_id): article = Article.objects.get(id=article_id) ctx = { "article" : article } return render(request, "detail.html", ctx) | cs |
comment_list를 삭제했지만 comment 데이터는 article 인스턴스에 고스란히 담겨있다.
지난 포스트에서 했던 것처럼 템플릿에서도 article 인스턴스에 접근하여 comment_list를 뽑아내면된다.
1 2 3 4 5 | <div> {% for comment in article.article_comments.all %} <div>{{ comment.username }} : {{ comment.content }}</div> {% endfor %} </div> | cs |
뷰에서 삭제한 comment_list의 값을 템플릿에서 그대로 사용했다. all 다음에 ()를 쓰지 않는다. 함수가 아니므로.
Comment 테이블의 article 필드에서 쓰인 "related_name" 치트가 ForeignKey로 연결된 Article 테이블에서 역으로 Comment 테이블에 접근하게 된다.