DB : N:1 ๊ด๊ณ
: ๋ฐ์ดํฐ๋ฒ ์ด์ค ๋ด ์ฌ๋ฌ ํ ์ด๋ธ ๊ฐ ๋ ผ๋ฆฌ์ ์ธ ์ฐ๊ฒฐ ๊ด๊ณ
1:1 (One to One) : ํ ๋ช
์ ์ฌ์ฉ์๋ ์ค์ง ํ๋์ ํ๋กํ์ ๊ฐ์ง. / ํ ํ
์ด๋ธ์ ๋ ์ฝ๋๊ฐ ๋ค๋ฅธ ํ
์ด๋ธ์ ๋จ ํ๋์ ๋ ์ฝ๋์๋ง 1:1 ๋งค์นญN:1 (Many to One) : ํ๋์ ๊ฒ์๊ธ์๋ ์ฌ๋ฌ ๊ฐ์ ๋๊ธ์ด ๋ฌ๋ฆด ์ ์๋ค. / ์ฌ๋ฌ ๊ฐ์ ๋ ์ฝ๋๊ฐ ํ๋์ ๋ ์ฝ๋์ ์์๋๋ ๊ด๊ณ (๋๊ธ๊ณผ ๊ฒ์๊ธ์ ๊ด๊ณ --> N : 1)N:M (Many to Many) : ํ ๋ช
์ ํ์์ ์ฌ๋ฌ ์์
์ ์ฒญ ๊ฐ๋ฅํ๋ค. ๋์์ ํ๋์ ์์
์ ์ฌ๋ฌ ํ์์ด ์๊ฐํ๋ค. / ์ค๊ฐ ํ
์ด๋ธ ํ์, ์ฌ๋ฌ ๋ ์ฝ๋๊ฐ ์ฌ๋ฌ ๋ ์ฝ๋์ ์๋ฐฉํฅ ์ฐ๊ฒฐ.ForeignKey(to, on_delete)
on_delete ์์ฑ ์ข ๋ฅ
: ์ง์ ๋์์ ์ ๋ณด๋ฅผ ์ ์ฅํ๊ณ ํ์ํ ๋ ํ์ฉํ๋ ๊ฒ
ex) comment.article.content
: ๋๊ฐ ๋๋ฅผ ์ฐธ์กฐํ๋์ง ๊ฑฐ๊พธ๋ก ์กฐํํ๋ ๊ฒ
article.comment_set.all()
๋ชจ๋ธ ์ธ์คํด์ค / ์ญ์ฐธ์กฐ ์ด๋ฆ(related manager) / QuerySetAPI
โป related manager ์ด๋ฆ ๊ท์น : ๋ชจ๋ธ ํด๋์ค๋ช
+ _set์ด ๊ธฐ๋ณธ๊ฐ์ผ๋ก, Django์์ ์๋์ผ๋ก ์์ฑํด์ค๋ค.
ํน์ ๋๊ธ์ ๊ฒ์๊ธ ์ฐธ์กฐ : comment.article
ํน์ ๊ฒ์๊ธ์ ๋๊ธ ๋ชฉ๋ก ์ญ์ฐธ์กฐ article.comment_set.all()
# articles/forms.py
from .models import Article, Comment
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('content',)
# articles / views.py
def detail(request, pk):
article = Article.objects.get(pk=pk)
comment_form = CommentForm()
context = {
'article': article,
'comment_form': comment_form,
}
return render(request, 'articles/detail.html', context)
<!-- articles/detail.html -->
<!-- ๊ฒ์๊ธ ์ ๋ณด ์ถ๋ ฅ ์ฝ๋ -->
<hr>
<form action="{% url 'articles:comments_create' article.pk %}" method="POST">
{% csrf_token %}
{{ comment_form }}
<input type="submit">
</form>
# articles/urls.py
app_name = 'article'
urlpatterns = [
. . .
path('<int:pk>/comments/', views.comments_create, name='comments_create'),
]
# articles/views.py
def comments_create(request, pk):
article = Article.objects.get(pk=pk)
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
comment = comment_form.save(commit=False)
comment.article = article
comment.save()
return redirect('articles:detail', article.pk)
context = {
'article' = article,
'comment_form': comment_form,
}
return render(request, 'articles/detail.html', context)
# articles / views.py
def detail(request, pk):
article = Article.objects.get(pk=pk)
comment_form = CommentForm()
context = {
'article': article,
'comment_form': comment_form,
'comments': comments,
}
return render(request, 'articles/detail.html', context)
# articles/urls.py
urlpatterns = [
. . .
path('<int:article_pk>/comments/<int:comment_pk>/delete/', views.comments_delete, name='comments_delete')
]
# articles/views.py
def comments_delete(request, article_pk, comment_pk):
comment = Comment.object.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>