参考
新規作成
モデルを作成して、それからマイグレーションファイルを作成する方法
INSTALLED_APPSへの追加
アプリケーションをプロジェクトに含めるため、mysite/settings.pyの"INSTALLED_APPS"を修正します。 デフォルトは以下のようになっています。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
新しいアプリケーションwords用に "words.apps.WordsConfig"を追加します。
INSTALLED_APPS = [
'words.apps.WordsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
モデル定義
以下のようなmysite/words/models.pyを作成します。 ここでは、wordテーブル用の定義を行っています。
from django.db import models
# Create your models here.
class Word(models.Model):
text = models.CharField(max_length=64)
description = models.TextField()
comment = models.TextField()
created = models.DateTimeField('created datetime')
updated = models.DateTimeField('updated datetime')
マイグレーションファイル作成
以下を実行してマイグレーションファイルを作成します。
python manage.py makemigrations [アプリケーション名]アプリケーション名がwordsの場合、実行結果は以下のようになり、最初のマイグレーションファイル"00001_initial.py"が作成されます。
$ python manage.py makemigrations words
Migrations for 'words':
words/migrations/0001_initial.py
- Create model Word
作成されたマイグレーションファイル mysite/words/migrations/0001_initial.py は以下のようになります。
# Generated by Django 2.2.1 on 2019-05-04 15:02
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Word',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('text', models.CharField(max_length=64)),
('description', models.TextField()),
('comment', models.TextField()),
('created', models.DateTimeField(verbose_name='created datetime')),
('updated', models.DateTimeField(verbose_name='updated datetime')),
],
),
]
作成されたマイグレーションファイル mysite/words/migrations/0001_initial.py のSQLを確認したい場合は、 以下のコマンドを実行します。
python manage.py sqlmigrate words [マイグレーション番号]
実行すると以下のようにSQLが表示されます。
$ python manage.py sqlmigrate words 0001 BEGIN; -- -- Create model Word -- CREATE TABLE `words_word` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `text` varchar(64) NOT NULL, `description` longtext NOT NULL, `comment` longtext NOT NULL, `created` datetime(6) NOT NULL, `updated` datetime(6) NOT NULL); COMMIT;
マイグレーション
例 マイグレーションの実行
$ python manage.py migrate
System check identified some issues:
WARNINGS:
?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default'
HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.2/ref/databases/#mysql-sql-mode
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, words
Running migrations:
Applying words.0001_initial... OK
作成済みのテーブル修正
作成済みテーブルを修正したい場合、モデル定義ファイルのmodels.py を変更します。 そのあと、マイグレーションファイルを作成して、マイグレーションを実行することになります。
モデル定義の修正
wordテーブルのcreatedとupdatedはNULL禁止ですが、手動で日時を登録する必要があります。 それより自動で登録、更新する方が楽なので、モデルを変更して、createdカラムは新規追加時に登録、updatedカラムは更新時に自動更新に変更します。
mysite/words/models.py
from django.db import models
# Create your models here.
class Word(models.Model):
text = models.CharField(max_length=64)
description = models.TextField()
comment = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
マイグレーションファイル作成
変更したmodels.pyからマイグレーションファイルを作成します。
$ python manage.py makemigrations words
Migrations for 'words':
words/migrations/0002_auto_20190507_2225.py
- Alter field created on word
- Alter field updated on word
作成されたマイグレーションファイル "0002_auto_20190507_2225.py"は以下になります。 2つ目のマイグレーションファイルのため、ファイル名先頭に"0002"が付いています。
# Generated by Django 2.2.1 on 2019-05-07 13:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('words', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='word',
name='created',
field=models.DateTimeField(auto_now_add=True),
),
migrations.AlterField(
model_name='word',
name='updated',
field=models.DateTimeField(auto_now=True),
),
]
mysite/words/migrations/0002_auto_20190507_2225.py
マイグレーション実行
$ python manage.py migrate words
System check identified some issues:
WARNINGS:
?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default'
HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.2/ref/databases/#mysql-sql-mode
Operations to perform:
Apply all migrations: words
Running migrations:
Applying words.0001_initial... OK
Applying words.0002_auto_20190507_2225... OK