반응형
https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/
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 %}
반응형
'Django' 카테고리의 다른 글
Django 모델이 생성된 후에 default date 컬럼 추가하기 (0) | 2022.02.10 |
---|---|
Queryset 역순으로 정렬하기 (How to reverse the order of query result) (0) | 2022.02.09 |
Django Models, Create Table, ForeignKey (0) | 2022.02.09 |
Django csft token with Ajax (0) | 2022.02.09 |
Django에 bootstrap 설치 (0) | 2022.02.08 |