| Comment | Article |
|---|---|
| id | id |
| content | title |
| created_at | content |
| updated_at | created_at |
| Article에 대한 외래 키 | updated_at |
class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) content = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)

| Option | Detail |
|---|---|
| CASCADE | Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey. |
| PROTECT | Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError. |
| RESTRICT | Prevent deletion of the referenced object by raising RestrictedError (a subclass of django.db.IntegrityError). Unlike PROTECT, deletion of the referenced object is allowed if it also references a different object that is being deleted in the same operation, but via a CASCADE relationship. |
| SET_NULL | Set the ForeignKey null; this is only possible if null is True. |
| SET_DEFAULT | Set the ForeignKey to its default value; a default for the ForeignKey must be set. |
| SET() | Set the ForeignKey to the value passed to SET(), or if a callable is passed in, the result of calling it. In most cases, passing a callable will be necessary to avoid executing queries at the time your models.py is imported: |
| DO_NOTHING | Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field. |
N:1 관계에서 1에서 N을 참조하거나 조회하는 것
N은 외래 키를 가지고 있어 물리적으로 참조가 가능하지만 1은 N에 대한 참조 방법이 존재하지 않아 별도의 역참조 긴으이 필요
article.comment_set.all()
특정 게시글에 작성된 댓글 전체를 조회하는 명령
'objects' 매니저를 통해 QuerySet API를 사용했던 것처럼 related manager를 통해 QuerySt API를 사용할 수 있게 됨
articles/forms.py from .models import Article, Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = '__all__'
articles/views.py from .forms import ArticleForm, CommentForm 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/models.py
from django.conf import settings
class Article(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
| get_user_model | settings.AUTH_USER_MODEL | |
|---|---|---|
| 반환값 | User Object(객체) | 'accounts.User' (문자열) |
| 사용 위치 | models.py가 아닌 다른 모든 위치 | models.py |
articles/views.py
@login_required
def create(request)
if request.method == 'POST':
form = ArticleForm(request.POST)
if form.is_valid():
article = form.save(commit=False)
article.user = request.user
article.save()
return redirect('articles:detail', article.pk)
else:
...
articles/views.py
@login_required
def update(request, pk):
article = Article.objects.get(pk=pk)
if request.user == article.user:
if request.method == 'POST':
form = ArticleForm(request.POST, instance=article)
if form.is_valid():
form.save()
return redirect('articles:detail', article.pky)
else:
form = ArticleForm(instance=article)
else:
return redirect('articles:index'):
...
artilces/views.py
@login_required
def delete(request, pk):
article = Article.objects.get(pk=pk)
if request.user == article.user:
article.delete()
return redirect('articles:index')