Python Django 入門トップページ


Django のマイグレーション

  1. 概要と準備
  2. マイグレーションの実行
  3. モデルの作成とマイグレーション
  4. テーブルに列を追加
  5. テストデータの投入
  6. ロールバックとテーブルの再生成
  7. テーブルに再び列を追加

Django のマイグレーション

モデルの作成とマイグレーション

まず,初期状態として Comment モデルには titlecreated_at だけを定義します.

comments/models.pyfrom django.db import models

# Create your models here.

class Comment(models.Model):
    title = models.CharField(max_length=200)
    created_at = models.DateTimeField(auto_now_add=True)

comments/migrations フォルダの中身を確認しておきます.

(py39) C:\Users\lecture\Documents\django\django_comment>dir comments\migrations ⏎
 ドライブ C のボリューム ラベルは OS です
 ボリューム シリアル番号は 9018-19A1 です

 C:\Users\lecture\Documents\django\django_comment\comments\migrations のディレクトリ

2022/08/01  18:09    <DIR>          .
2022/08/01  18:09    <DIR>          ..
2022/08/01  18:08                 0 __init__.py
2022/08/01  18:09    <DIR>          __pycache__
               1 個のファイル                   0 バイト
               3 個のディレクトリ  86,372,159,488 バイトの空き領域

(py39) C:\Users\lecture\Documents\django\django_comment>

マイグレーションファイルを作成します.

(py39) C:\Users\lecture\Documents\django\django_comment>python manage.py makemigrations comments ⏎
Migrations for 'comments':
  comments\migrations\0001_initial.py
    - Create model Comment

(py39) C:\Users\lecture\Documents\django\django_comment>

ファイルが作成されたことを確認します.

(py39) C:\Users\lecture\Documents\django\django_comment>dir comments\migrations ⏎
 ドライブ C のボリューム ラベルは OS です
 ボリューム シリアル番号は 9018-19A1 です

 C:\Users\lecture\Documents\django\django_comment\comments\migrations のディレクトリ

2022/08/01  18:17    <DIR>          .
2022/08/01  18:17    <DIR>          ..
2022/08/01  18:17               586 0001_initial.py
2022/08/01  18:08                 0 __init__.py
2022/08/01  18:09    <DIR>          __pycache__
               2 個のファイル                 586 バイト
               3 個のディレクトリ  86,371,938,304 バイトの空き領域

(py39) C:\Users\lecture\Documents\django\django_comment>

作成された 0001_initial.py の内容は次の通りです.

comments/migrations/0001_initial.py# Generated by Django 4.0.6 on 2022-08-01 18:17

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Comment',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=200)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
            ],
        ),
    ]

マイグレーションファイルが作成されましたが,まだ python manage.py migrate コマンドは実行されていないので,データベースへ反映(テーブル作成)されていません.

(py39) C:\Users\lecture\Documents\django\django_comment>python manage.py showmigrations ⏎
admin
 [X] 0001_initial
 [X] 0002_logentry_remove_auto_add
 [X] 0003_logentry_add_action_flag_choices
auth
 [X] 0001_initial
 [X] 0002_alter_permission_name_max_length
 [X] 0003_alter_user_email_max_length
 [X] 0004_alter_user_username_opts
 [X] 0005_alter_user_last_login_null
 [X] 0006_require_contenttypes_0002
 [X] 0007_alter_validators_add_error_messages
 [X] 0008_alter_user_username_max_length
 [X] 0009_alter_user_last_name_max_length
 [X] 0010_alter_group_name_max_length
 [X] 0011_update_proxy_permissions
 [X] 0012_alter_user_first_name_max_length
comments
 [ ] 0001_initial
contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
sessions
 [X] 0001_initial

(py39) C:\Users\lecture\Documents\django\django_comment>

データベースのテーブル一覧も確認しておきます.

sqlite> .tables ⏎
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>

データベースへ反映させます.

(py39) C:\Users\lecture\Documents\django\django_comment>python manage.py migrate ⏎
Operations to perform:
  Apply all migrations: admin, auth, comments, contenttypes, sessions
Running migrations:
  Applying comments.0001_initial... OK

(py39) C:\Users\lecture\Documents\django\django_comment>

結果を確認します.

(py39) C:\Users\lecture\Documents\django\django_comment>python manage.py showmigrations ⏎
admin
 [X] 0001_initial
 [X] 0002_logentry_remove_auto_add
 [X] 0003_logentry_add_action_flag_choices
auth
 [X] 0001_initial
 [X] 0002_alter_permission_name_max_length
 [X] 0003_alter_user_email_max_length
 [X] 0004_alter_user_username_opts
 [X] 0005_alter_user_last_login_null
 [X] 0006_require_contenttypes_0002
 [X] 0007_alter_validators_add_error_messages
 [X] 0008_alter_user_username_max_length
 [X] 0009_alter_user_last_name_max_length
 [X] 0010_alter_group_name_max_length
 [X] 0011_update_proxy_permissions
 [X] 0012_alter_user_first_name_max_length
comments
 [X] 0001_initial
contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
sessions
 [X] 0001_initial

(py39) C:\Users\lecture\Documents\django\django_comment>

データベースのテーブル一覧を表示し,テーブルの定義についても確認します.

sqlite> .tables ⏎
auth_group                  comments_comment
auth_group_permissions      django_admin_log
auth_permission             django_content_type
auth_user                   django_migrations
auth_user_groups            django_session
auth_user_user_permissions
sqlite>
sqlite> .schema comments_comment ⏎
CREATE TABLE IF NOT EXISTS "comments_comment" (
      "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
      "title" varchar(200) NOT NULL,
      "created_at" datetime NOT NULL
);
sqlite>

目次に戻る