Django

Djnago Model Relationship (1:N)

monster route 2024. 8. 19. 04:31

 

댓글(Comment) 구현하기

 

articles/models.py

class Comment(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    content = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.content

 

그 다음에 마이그래이션 해주면, 속성값이 생긴걸 확인할 수 있다.

 

 

자, 그럼 댓글 달기 해보자.

 

 

ORM 사용해보기

 

→ 터미널에서 아래 코드 입력

  • python manage.py shell_plus
  • comment = Comment()
  • comment.content = “first comment”
  • comment.save()

 

Comment 생성하기

 

오류가 엄청 뜬다..😟

article_id 값을 지정하지 않았기때문에 그렇다.

 

 

두번째 댓글 생성하기

 

 

comment → article 접근

 

  ✏️ 그럼  comment에서 어떤 article인지 접근하고 싶다면?

 

  ✏️ 이 comment가 작성된 article의 titlecontent를 알고 싶다면?

 

 

article → comments 접근

 ✏️ 1번 Article에 작성된 모든 Comment 조회

 

 

편하긴 한데 _set 빼고

→ article.commnets.all() 이렇게 쓰고 싶어🤔

 

models.py 

class Comment(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name="comments")
    content = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.content

 

related_name="comments" 를 추가해준다.

 

그 다음, 다시 마이그래이션 해주고 

 

다시 shell_plus 켜서 확인해보면 comments로 했을때 잘 나온다.👍

 


 

댓글 생성

 

articles/urls.py

path("<int:pk>/comments/", views.comments_create, name="comments_create"),

 

forms.py

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = "__all__"
        exclude = ("article",)

 

articles/views.py

@require_POST
def comment_create(request, pk):
    article = get_object_or_404(Article, pk=pk)
    form = CommentForm(request.POST)
    if form.is_valid():
        comment = form.save(commit=False)
        comment.article = article
        comment.save()
    return redirect("articles:article_detail", article.pk)

 

article_detail.html 변경

<hr>
<h3>댓글</h3>
<form action="{% url "articles:comment_create" article.pk %}" method="POST">
    {% csrf_token %}
    {{ comment_form.as_p }}
    <input type="submit" value="댓글작성">
</form>

 

 

근데 댓글을 썼는데..

 

 

댓글이 안보임ㅋㅋㅋㅋ 

 

 

 

댓글 보이게 코드 수정해야함😂

 

articles/views.py

def article_detail(request, pk):
	article = get_object_or_404(Article, pk=pk)
	comment_form = CommentForm()
	comments = article.comment_set.all()
	context = {
		"article": article,
		"comment_form": comment_form,
		"comments": comments, 
		}
	return render(request, "articles/article_detail.html", context)

 

❓근데 궁금한게.. 아까 우리 comment_set 이거 comments로 바꿔줬는데 그럼 그냥 comments로 써도 되는건가..🤔 

 

 

article_detail.html 추가

...
<ul>
    {% for comment in comments %}
        <li>
            <p>{{ comment.content }}</p>
        </li>
    {% endfor %}
</ul>

 

 

근데 저 뷰 수정 안하고 그냥 article_detail.html 여기 코드만 추가해서 해결하는 것도 가능하다.

<ul>
    {% for comment in articles.comments.all %}
        <li>
            <p>{{ comment.content }}</p>
        </li>
    {% endfor %}
</ul>

 

 

근데 그냥 난 위에 걸로 함

 

서버 실행하면

????? 

아까의 궁금증이.. ? 혹시나 하고 comments로 바꿔봤더니 

 

해결됨! 오👍

 

 

그럼 댓글 삭제 기능전체 댓글의 수를 보여주는 기능을 구현해보자.

 

 

만들긴 만들었는데....

삭제누르면 오류가 뜸..ㅠㅠ엉엉

 

일단.. 완강을 해야하니.. Custom UserModel 공부하고 다시 해보는걸로ㅠㅠ😥