Django
Django ForeignKey 데이터 가져오기
jwstory.com
2022. 2. 9. 16:34
반응형
https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/
Many-to-one relationships | Django documentation | Django
Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate
docs.djangoproject.com
Comment와 Post는 Many to One 관계이다.
이런 경우 특정 Post에 대한 Comment 전체를 가져오려면 아래와 같이 코딩한다.
comment = Comment.objects.filter(post__id=post_id)
재미 있는 것은 __를 사용한다는 것이다.
이렇게 하여 QuerySet 객체를 리턴한다.
실제로 아래와 같이 구현 가능하다.
View
def post_detail(request, post_id):
post = Post.objects.get(pk=post_id)
comment = Comment.objects.filter(post__id=post_id)
return render(request, "HelloWorld/post_detail.html", {'post': post, 'comments':comment})
Template
{% for comment in comments %}
<span>{{ comment.post_comment }}</span>
{% endfor %}
반응형