구름을 이용한 점프 투 장고-2장(이어서)

이주석·2021년 6월 23일
0
post-thumbnail

2장 : 장고의 기본 요소 익히기.

2-2 데이터를 관리하는 모델


1. 데이터를 관리하는 모델이란?

  • 일반적으로 웹 개발에서 데이터 저장 & 조회 하기 위해 SQL쿼리문을 사용한다.
    이 말은 즉 데이터를 저장 & 조회 하기 위해서 별도의 SQL 쿼리문을 공부해야 한다는 말과 같다.
    공부할게 한 개 더 생기는 거와 같다.
    하지만 모델이라는 것을 사용하면 SQL쿼리문을 몰라도 데이터를 저장 & 조회할 수 있다.


2. migrate와 테이블 알아보기.

 [1] 장고 개발 서버 구동 시 나오는 경고 메시지 살펴보기

 모델을 알아보기 위해 python manage.py runserver 명령 실행 시 나오는 경고 메시지를 조금 더 자세히
 살펴보자. 중간쯤에 있는 경고 메시지를 보면 'You have 18 unapplied migration(s)'
 해석해보면 "아직 적용되지 않은 18개의 migration이 있다" 고 한다.

[명령 프롬포트]

root@goorm : /workspace/mystie# python manage.py runserver

/workspace/mystie> python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
May 06, 2020 - 09:49:37
Django version 3.1.3, using settings 'config.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.


위 경고 메시지가 admin, auth, contenttypes, sessions 앱과 관련된 내용이며, 이 오류를 해결하려면 python manage.py migrate를 실행해야 한다는 안내는 확인할 수 있다.

 [2] migrate 명령으로 앱이 필요로 하는 테이블 생성하기

[명령 프롬포트]

root@goorm : /workspace/mystie# python manage.py migrate

Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying sessions.0001_initial... OK


메시지는 migrate를 통해 admin, auth, contenttypes, sessions 앱이 사용하는 테이블이 생성되었음을 알려준다. 이 테이블 관련해서는 깊게 알 필요가 없다. 왜냐하면 건드릴 일이 거의 없기 때문이다.


3. 모델 만들기

이제 파이보에서 사용할 모델을 만들어 보자. 파이보는 질문 답변 게시판이므로 질문과 답변에 해당하는 모델이 있어야 한다.

 [1] 모델 속성 구상하기

 질문 모델에는 다음과 같은 속성이 필요하다.

속성명 설명
subject 질문의 제목
content 질문의 내용
create_date 질문을 작성한 일시

 답변 모델에는 다음과 같은 속성이 필요하다.

속성명 설명
question 질문(어떤 질문의 답변인지 알아야 하므로 질문 속성이 필요함)
content 답변의 내용
create_date 답변을 작성한 일시

 [2] pybo/models.py에 질문 모델 작성하기

[파일 경로 : /workspace/mysite/pybo/models.py]

  from django.db import models
# ---------------------------------- [edit] ---------------------------------- #
class Question(models.Model): 
    subject = models.CharField(max_length=200)
    content = models.TextField()
    create_date = models.DateTimeField()
# ---------------------------------------------------------------------------- #

위에서 subject 는 글의 제목, content는 글의 내용, create_date는 쓴 시간을 기록한다.

 [3] pybo/models.py에 답변 모델 작성하기

[파일 경로 : /workspace/mysite/pybo/models.py]

from django.db import models
class Question(models.Model):
    subject = models.CharField(max_length=200)
    content = models.TextField()
    create_date = models.DateTimeField()
  # ---------------------------------- [edit] ---------------------------------- #
class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    content = models.TextField()
    create_date = models.DateTimeField()
# ---------------------------------------------------------------------------- #

위에서 Answer 모델은 질문에 대한 답변이므로 Question 모델을 속성으로 가져야 된다. 이렇게 다른 모델을 속성으로 가지려면 ForeignKey를 이용한다. ForeignKey는 쉽게 말해 다른 모델과의 연결을 의미하며, on_delete=models.CASCADE는 답변에 연결된 질문이 삭제되면 답변도 함께 삭제하라는 의미이다.

 [4] config/setting.py 에 pybo 앱 등록하기

[파일 경로 : /workspace/mysite/config/settings.py]

(... 생략 ...)
INSTALLED_APPS = [
# ---------------------------------- [edit] ---------------------------------- #
    'pybo.apps.PyboConfig',
# ---------------------------------------------------------------------------- #
    'django.contrib.admin',
    'django.contrib.auth',
    (... 생략 ...)
]
(... 생략 ...)

 [5] migrate로 테이블 생성하기

   makemigrations로 테이블 작업 파일 생성하기.

[명령 프롬포트]

root@goorm : /workspace/mystie# python manage.py makemigrations
Migrations for 'pybo':
 pybo\migrations\0001_initial.py
  - Create model Question
  - Create model Answer

 [6] migrate 실행하기

[명령 프롬포트]

root@goorm : /workspace/mystie# python manage.py migrate
Operations to perform:
 Apply all migrations: admin, auth, contenttypes, pybo, sessions
Running migrations:
 Applying pybo.0001_initial... OK

여기까지 잘 따라왔으면 실제 테이블을 잘 만든 것이다.


  • 참고 사이트 : https://wikidocs.net/72280
  • 해당 게시물은 위키독스에 있는 '점프 투 장고' 책을 정리한 내용입니다.
  • 본 게시물은 개인적인 용도로 작성된 게시물입니다.
    이후 포트폴리오로 사용될 정리 자료이니 불펌과 무단도용은 하지 말아주시고,
    개인 공부 목적으로만 이용해주시기 바랍니다.
profile
Juseok Lee

0개의 댓글

관련 채용 정보