본문 바로가기
개발 일지

TIL(24.05.09)

by 만식 2024. 5. 9.

 

출처 : https://online.spartacodingclub.kr/enrolleds/66134275f7c0c6ab299bed92/rounds/661341fdd9c7e6af9aaf398d/roadmap

 

스파르타코딩클럽

스파르타코딩클럽 | 올해의 브랜드 대상 1위 왕초보를 위한 온라인 코딩강의

online.spartacodingclub.kr

 

Many to one relationships

 

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
# articles/models.py

 

...
class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = "__all__"
        # forms.py (1차)

 

...
<hr>
<h3>댓글</h3>
<form action="#" method="POST">
    {% csrf_token %}
    {{ comment_form.as_p }}
    <input type="submit" value="댓글작성">
</form>
# article_detail.html

 

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

 

path("<int:pk>/comments/", views.comments_create, name="comments_create"),
# articles/urls.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)
    # articles/views.py

 

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

 

...
<ul>
    {% for comment in comments %}
        <li>
            <p>{{ comment.content }}</p>
        </li>
    {% endfor %}
</ul>
# article_detail.html에 추가

굉장히 흔히 사용되는 관계

1:N 관계 예시

  • 만약 Article에 Author라는 개념을 둔다면,
    • 하나의 Article은 한 명의 Author를 가질 수 있음
    • 한 명의 Author는 여러 개의 Article을 가질 수 있음
  • 만약 Article에 Comment라는 개념을 둔다면,
    • 하나의 Article은 여러개의 Comment를 가질 수 있음
    • 하나의 Comment는 하나의 Article을 가질 수 있음

Foreign Key

  • 외래키를 의미
  • 관계형 데이터베이스에서 한 테이블(A)의 필드 중 다른 테이블(B)의 행을 유일하게 식별이 가능한 키
  • 테이블(A)에 설정되는 Foreign Key가 반드시 다른 테이블(B)의 Primary Key일 필요는 없으나 유일하게 식별이 가능해야 함

 

'개발 일지' 카테고리의 다른 글

데이터베이스와 SQL (24.05.13)  (1) 2024.05.13
TIL(24.05.10)  (1) 2024.05.10
TIL(24.05.08)  (1) 2024.05.08
TIL (24.05.07)  (1) 2024.05.07
TIL(24.05.03)  (0) 2024.05.07