고객 테이블
: 고객 정보주문 테이블
: 주문 정보주문id | 고객id |
---|---|
제품명 | 이름 |
주문일 | 주소지 |
배송일 | 배송지 |
주문상태 |
이렇게 저장하면 동명 이인 구분 불가능
주문id | 제품명 | 주문일 | 배송일 | 주문상태 | 고객정보 |
---|---|---|---|---|---|
1 | 생수 | 2000-01-01 | 2000-01-01 | 배송중 | 김진수 |
2 | 영양제 | 2000-01-01 | 2000-01-01 | 배송 준비중 | 박영희 |
3 | 음료수 | 2000-01-01 | 2000-01-01 | 배송중 | 김진수 |
이렇게 저장하면 동명 이인 구분 가능
주문id | 제품명 | 주문일 | 배송일 | 주문상태 | 고객정보 |
---|---|---|---|---|---|
1 | 생수 | 2000-01-01 | 2000-01-01 | 배송중 | 2 |
2 | 영양제 | 2000-01-01 | 2000-01-01 | 배송 준비중 | 1 |
3 | 음료수 | 2000-01-01 | 2000-01-01 | 배송중 | 2 |
관계형 데이터베이스에서 다른 테이블의 행을 식별할 수 있는 키
참조되는 테이블의 기본 키를 가리킴
키를 사용하여 부모 테이블의 유일한 값을 참조
게시글
: n개의 댓글을 가진다.
댓글
: 1개의 게시글에 속한다.
OneToOneField()
ForeignKey()
ManyToManyField()
one-to-many
ralationship을 담당하는 Django의 모델 필드 클래스model class
on_delete
옵션부모 객체가 삭제되었을 때 이를 참조하는 객체도 삭제
Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.
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.
ForeignKey argument에 Article을
객체
로 그냥 사용해도 오류가 없다.
class Article(models.Model):
...
class Comment(models.Model):
...
article = models.ForeignKey(Article, on_delete=models.CASCADE)
Article 객체 대신 'Article'
문자열
로 사용하면 된다.
class Comment(models.Model):
...
article = models.ForeignKey('Article', on_delete=models.CASCADE)
class Article(models.Model):
...
from django.db import models
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill
# Create your models here.
class Article(models.Model):
...
class Comment(models.Model):
content = models.TextField()
created_at = models.DateTimeField(auto_now_add = True)
article = models.ForeignKey('Article', on_delete=models.CASCADE)
# admin에서 확인 위해 admin항목에 Comment를 추가해준다.
from django.contrib import admin
from .models import Article, Comment
# Register your models here.
class ArticleAdmin(admin.ModelAdmin):
list_display = ('title','created_at','updated_at')
class CommentAdmin(admin.ModelAdmin):
list_display = ('content','created_at','article')
admin.site.register(Article, ArticleAdmin)
admin.site.register(Comment,CommentAdmin)
직접 참조 역참조 객체 구분 적는 순서로 파악 가능
...
def detail(request, pk):
article = Article.objects.get(pk=pk)
comments = article.comment_set.all()
context={
'article':article,
'comments':comments
}
return render(request,'articles/detail.html', context)
...
{% for comment in comments %}
<p>{{ comment.content }}</p>
{% endfor %}
{% if comments %}
{% for comment in comments %}
<p>{{ comment.content }}</p>
{% endfor %}
{% else %}
<p>댓글이 없습니다.</p>
{% endif %}
{% for comment in comments %}
<p>{{ comment.content }}</p>
{% empty %}
<p>댓글이 없습니다.</p>
{% endfor %}
from .models import Article, Comment
...
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['content']
...
from .forms import ArticleForm, CommentForm
def detail(request, pk):
...
comment_form = CommentForm
context={
...
'comment_form':comment_form,
}
return render(request,'articles/detail.html', context)
...
<h2>댓글</h2>
<form action="">
{% bootstrap_form comment_form %}
{% bootstrap_button button_type='submit' content='OK' %}
</form>
<hr>
...
path('<int:pk>/comments/', views.comment_create, name='comment_create'),
def comment_create(request, pk):
article = Article.objects.get(pk=pk)
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
comment_form.save()
return redirect('articles:detail', article.pk)
...
<h2>댓글</h2>
<form action="{% url 'articles:comment_create' article.pk %}" method='POST'>
{% csrf_token %}
{% bootstrap_form comment_form layout='inline' %}
{% bootstrap_button button_type='submit' content='OK' %}
</form>
...
에러가 뜬다
사용자가 입력하는 값 이 외에도 추가로 입력해주어야 하는 정보가 있어서 일단 저장을 멈추고 추가 정보를 넘겨준 후 저장하는 방법!!
def comment_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)
CommentForm클래스의 인스턴스 comment_form
Comment 클래스의 인스턴스 comment
=> 모델폼의 save 메서드는 리턴 값이 그 모델의 인스턴스이다.