데이터 분석 기술 블로그

DB에 대하여(3)_댓글 생성 연습 (feat. Django) 본문

DB

DB에 대하여(3)_댓글 생성 연습 (feat. Django)

데이터분석가 이채은 2024. 4. 18. 09:00

1. shell_plus 실행 및 게시글 작성

python manage.py shell_plus

# 게시글 생성
Article.objects.create(title='title', content='content')

2. 댓글 생성

# Comment 클래스의 인스턴스 comment 생성
comment = Comment()

# 인스턴스 변수 저장
comment.content = 'first comment'

# DB에 댓글 저장
comment.save()

# 에러 발생
django.db.utils.IntegrityError: NOT NULL constraint failed:
articles_comment.article_id
# articles_comment 테이블의 ForeignKeyField, article_id 값이 저장 시 누락되었기 때문

3. shell_plus 실행 및 게시글 작성

# 게시글 조회
article = Article.objects.get(pk=1)

# 외래 키 데이터 입력
comment.article = article
# 또는 comment.article_id = article.pk 처럼 pk 값을 직접 외래 키 컬럼에
# 넣어 줄 수도 있지만 권장하지 않습니다.

# 댓글 저장 및 확인
comment.save()

4. comment 인스턴스를 통한 article 값 참조하기

comment.pk
=> 1
comment.content
=> 'first comment'

# 클래스 변수명인 article로 조회 시 해당 참조하는 게시물 객체를 조회할 수 있습니다.
comment.article
=> <Article: Article object (1)>

# article_pk는 존재하지 않는 필드이기 때문에 사용 불가
comment.article_id
=> 1

5. shell_plus 실행 및 게시글 작성

# 1번 댓글이 작성된 게시물의 pk 조회
comment.artcle.pk
=> 1

# 1번 댓글이 작성된 게시물의 content 조회
comment.article.content
=> 'content'

6. 두 번째 댓글 생성

comment = Comment(content='second comment', article=article)
comment.save()

comment.pk
=> 2

comment
=> <Comment: Comment object (2)>

comment.article.pk
=> 1

7. 작성된 댓글 데이터 확인