Tags
- 뷰
- 쟝고
- 큐
- Vue
- regexp
- 이진트리
- SQL
- Article & User
- 그리디
- Queue
- DB
- M:N
- migrations
- 완전검색
- ORM
- 백트래킹
- distinct
- Tree
- N:1
- Django
- 트리
- 통계학
- delete
- count
- stack
- 스택
- create
- outer join
- update
- drf
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Notice
Recent Posts
Link
데이터 분석 기술 블로그
DB에 대하여(6)_댓글 READ & DELETE (feat. Django) 본문
1. 댓글 READ 구현
detail view 함수에서 전체 댓글 데이터를 조회
# articles/views.py
from .models import Article, Comment
def detail(request, pk):
article = Article.objects.get(pk=pk)
comment_form = CommentForm()
comments = article.comment_set.all()
context = {
'article': article,
'comment_form': comment_form,
'comments': comments,
}
return render(request, 'articles/detail.html', context)
<!-- articles/detail.html -->
<h4>댓글 목록</h4>
<ul>
{% for comment in comments %}
<li>{{ comment.content }}</li>
{% endfor %}
</ul>
2. 댓글 DELETE 구현
댓글 삭제 url 작성
# articles/urls.py
app_name = 'articles'
urlpatterns = [
...,
path('<int:article_pk>/comments/<int:comment_pk>/delete/',
views.comments_delete,
name='comments_delete'
),
]
댓글 삭제 view 함수 정의
# articles/views.py
from .models import Article, Comment
def comments_delete(request, article_pk, comment_pk):
comment = Comment.objects.get(pk=comment_pk)
comment.delete()
return redirect('articles:detail', article_pk)
<!-- articles/detail.html -->
<ul>
{% for comment in comments %}
<li>
{{ comment.content }}
<form action="{% url 'articles:comments_delete' article.pk comment.pk %}" method="POST">
{% csrf_token %}
<input type="submit" value="DELETE">
</form>
</li>
{% endfor %}
</ul>
참고
1. admin site 등록
Comment 모델을 admin site에 등록해 CRUD 동작 확인하기
# articles/admin.py
from .models import Article, Comment
admin.site.register(Article)
admin.site.register(Comment)
2. 댓글이 없는 경우 대체 콘텐츠 출력
DTL 'for empty' 태그 사용
<!-- articles/detail.html -->
{% for comment in comments %}
<li>
{{ comment.content }}
<form action="{% url 'articles:comments_delete' article.pk comment.pk %}" method="POST">
{% csrf_token %}
<input type="submit" value="DELETE">
</form>
</li>
{% empty %}
<p>댓글이 없어요..</p>
{% endfor %}
3. 댓글 개수 출력하기
DTL filter - 'length' 사용
{{ comments|length }}
{{ article.comment_set.all|length }}
QuerysetAPI - 'count()' 사용
{{ article.comment_set.count }}
'DB' 카테고리의 다른 글
DB에 대하여(7)_Article & User 게시글 CREATE (feat. Django) (0) | 2024.04.23 |
---|---|
DB에 대하여(7)_Article & User 모델 관계 설정 (feat. Django) (0) | 2024.04.22 |
DB에 대하여(5)_댓글 CREATE (feat. Django) (0) | 2024.04.20 |
DB에 대하여(4)_관계 모델 참조 (feat. Django) (0) | 2024.04.19 |
DB에 대하여(3)_댓글 생성 연습 (feat. Django) (0) | 2024.04.18 |