Tags
- DB
- ORM
- M:N
- 완전검색
- regexp
- Queue
- N:1
- 통계학
- 스택
- 이진트리
- 뷰
- SQL
- create
- Tree
- 백트래킹
- Vue
- Article & User
- migrations
- distinct
- delete
- Django
- update
- 큐
- 그리디
- count
- drf
- stack
- 쟝고
- 트리
- outer join
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Notice
Recent Posts
Link
데이터 분석 기술 블로그
DB에 대하여(3)_댓글 생성 연습 (feat. Django) 본문
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. 작성된 댓글 데이터 확인
'DB' 카테고리의 다른 글
DB에 대하여(6)_댓글 READ & DELETE (feat. Django) (0) | 2024.04.21 |
---|---|
DB에 대하여(5)_댓글 CREATE (feat. Django) (0) | 2024.04.20 |
DB에 대하여(4)_관계 모델 참조 (feat. Django) (0) | 2024.04.19 |
DB에 대하여(2)_댓글 모델 구현 (feat. Django) (0) | 2024.04.17 |
DB에 대하여(1)_Many to one relationships 개요 (0) | 2024.04.16 |