Django에서 데이터베이스를 생성하고 데이터베이스에 사용되는 테이블과 필드를 생성하기 위하여 모델(Model)을 정의하는 테스트를 하고 내용을 정리합니다.
데이터베이스(SQLite) 생성
Django에서는 기본적으로 SQLite를 사용하도록 구성되어 있습니다. SQLite는 Python에서 기본으로 제공되고 Django 설정에도 SQLite를 사용하도록 되어 있습니다.
그 코드는 settings.py 파일에서 확인할 수 있고 아래와 같습니다.
# jackerlab_django/settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
다른 데이터 베이스를 설치하고 설정하는 것에 대해서는 다음에 다룰 수 있도록 하겠습니다.
SQLite 데이터베이스에 테이블을 생성해 보겠습니다.
아래 명령어를 실행하면 데이터베이스가 생성되고 Django에서 제공하는 테이블들이 자동으로 생성되는 것을 확인할 수 있습니다.
그리고 이 데이터페이스 파일은 ‘db.sqlite3’ 이라는 이름으로 생성됩니다.
$ python manage.py migrate
PS D:\Python_Project\Django_test> 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 sessions.0001_initial... OK
PS D:\Python_Project\Django_test>

생성된 데이터베이스와 테이블은 SQLite에 접속해서 확인할 수 있고 간단하게 아래와 같이 진행하면 되겠습니다.
PS D:\Python_Project\Django_test> sqlite3 db.sqlite3
SQLite version 3.26.0 2018-12-01 12:34:55
Enter ".help" for usage hints.
sqlite>
sqlite> .database
main: D:\Python_Project\Django_test\db.sqlite3
sqlite>
sqlite> .table
auth_group auth_user_user_permissions
auth_group_permissions django_admin_log
auth_permission django_content_type
auth_user django_migrations
auth_user_groups django_session
sqlite>
sqlite> .quit
PS D:\Python_Project\Django_test>
모델(Model) 생성
모델은 부가적인 메타데이터를 가진 데이터베이스의 구조(layout)를 말합니다.
모델에 테이블을 정의하고 각 테이블의 필드를 정의하는 정도로 생각할 수 있겠습니다.
모델은 models.py라는 파일에서 정의할 수 있습니다.
# apps/models.py
from django.db import models
class Info(models.Model):
title_text = models.CharField(max_length=50)
content_text = models.CharField(max_length=200)
create_date = models.DateTimeField('date published')
위 코드는 데이터베이스에 Info 라는 테이블을 만들고 title_text, content_ext, create_date 3개의 필드를 정의하겠다는 의미입니다.
각 필드마다 Type 등을 정의할 수 있습니다.
CharField()는 문자 필드를 의미하고 DateTimeField는 날짜와 시간필드를 표현합니다.
모델에 대한 자세한 내용은 다음에 다룰 수 있도록 하겠습니다.
앱(App) 추가 및 모델 활성화
우선 Django에게 우리가 생각한 앱을 사용할 것이라는 것을 알려야 합니다.
우리가 만든 앱을 현재 프로젝트에 포함시키기 위해서는 앱의 구성 클래스에 대한 참조를 INSTALLED_APPS 설정에 추가해야 합니다. AppsConfig 클래스는 apps/apps.py 파일에 존재하고 아래와 같이 정의되어 있습니다.
# apps/apps.py
from django.apps import AppConfig
class AppsConfig(AppConfig):
name = 'apps'
이 클래스를 우리의 앱을 참조하도록 추가하면 되겠습니다. 추가하는 형식은 경로 및 클래스 명으로 지정하면 되고 점으로 경로를 구분하면 됩니다.
# jackerlab_django/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps.apps.AppsConfig',
# 또는 'apps',
]
이제 Django는 우리가 생성한 앱(Apps)이 포함된 것을 알게 되었고 우리가 구성한 모델이 생성되었다는 것을 알려주고 저장을 하도록 합니다.
참고로 위와 같이 AppConfig 클래스만이 아닌 apps 전체를 알려주어도 됩니다.
$ python manage.py makemigrations [앱이름]
PS D:\Python_Project\Django_test> python manage.py makemigrations apps
Migrations for 'apps':
apps\migrations\0001_initial.py
- Create model Info
PS D:\Python_Project\Django_test>

위와 같이 명령어를 수행하면 Django에게 모델(데이터베이스 스키마)을 알려주고 저장하는 역할을 하며 Django는 디스크상에 파일로 생성을 합니다.
이제 migrate 명령어를 이용하여 데이터베이스에 모델과 관련된 테이블을 생성합니다.
PS D:\Python_Project\Django_test> python manage.py migrate
Operations to perform:
Apply all migrations: admin, apps, auth, contenttypes, sessions
Running migrations:
Applying apps.0001_initial... OK
PS D:\Python_Project\Django_test>
참고로 테이블을 확인하는 방법은 아래와 같고 sqlite3으로 접속해서 확인하면 apps_info 테이블이 생성된 것을 확인 할 수 있고 스키마를 확인하면 모델에서 정의한 필드들이 포함되어 있습니다.
PS D:\Python_Project\Django_test> sqlite3 db.sqlite3
SQLite version 3.26.0 2018-12-01 12:34:55
Enter ".help" for usage hints.
sqlite> .table
apps_info auth_user_user_permissions
auth_group django_admin_log
auth_group_permissions django_content_type
auth_permission django_migrations
auth_user django_session
auth_user_groups
sqlite> .schema apps_info
CREATE TABLE IF NOT EXISTS "apps_info" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title_text" varchar(50) NOT NULL,
"content_text" varchar(200) NOT NULL, "create_date" datetime NOT NULL);
sqlite>
여기까지 데이터베이스를 생성하고 모델을 정의하여 테이블 및 필드를 추가하는 내용까지 진행하였습니다.
참고 사이트
ㅇ https://docs.djangoproject.com/ko/2.1/intro/
sqlite3 db.sqlite3을 입력하면 sqlite3 이 실행되어야 하는데 저는 안되는데 이유를 알 수 있을까요.. (파이썬3 및 장고 설치완료 했습니다.)
–에러 문구–
sqlite3 : ‘sqlite3’ 용어가 cmdlet, 함수, 스크립트 파일 또는 실행할 수 있는 프로그램 이름으로 인식되지 않습니다. 이름이 정확한지 확인하고 경로가 포함된 경우 경로가 올바른지 검증한 다음 다시 시도하십시오.