Python Django 入門トップページ


Django によるコメント掲示板の開発:目次

  1. プロジェクトの作成
  2. Git でコミット
  3. Web サーバを起動しておく
  4. Config
  5. Comments アプリケーションを作る
  6. アプリケーションを有効にする
  7. はじめてのビューを作成する
  8. モデルを作る
  9. マイグレーション
  10. テストデータの設定
  11. データベースからコメント一覧を取得して表示してみよう
  12. Bootstrap の導入
  13. コメントの詳細表示
  14. urls.pyの書き方
  15. HTML のテンプレート化
  16. コメントの新規投稿
  17. コメントの編集機能を追加する
  18. さらにテンプレート化
  19. モデル,マイグレーションファイル,フォームの関連
  20. 入力内容の検証(バリデーション)
  21. コメントを削除する
  22. 一覧を逆順にする
  23. ページネーション
  24. フラッシュメッセージ
  25. Static コンテンツの設置
  26. 更新や削除にもフラッシュメッセージを表示
  27. テストの自動化を実現しよう
  28. デバッグツールバーを使う
  29. generic モジュールを使わずにコメント一覧を取得する
  30. コメント一覧のページネーション
  31. 一覧の表示順序を制御する
  32. generic モジュールを使わずにコメントの詳細を表示する
  33. コメント詳細にページ送り機能を作成する
  34. generic モジュールを使わずにコメント登録機能を作成する
  35. generic モジュールを使わずにコメント編集機能を作成する
  36. generic モジュールを使わずにコメント削除機能を作成する

Django によるコメント掲示板の開発

マイグレーション

モデル (models.py) からマイグレーションファイルを作成します.

(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>

この作業によって comments/migrations/0001_initial.py ファイルが生成されたので内容を確認しておこう.このファイルの内容に従ってデータベースにテーブルが定義されることになります.

comments/migrations/0001_initial.py# Generated by Django 4.0.6 on 2022-07-27 11:19

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)),
                ('body', models.CharField(max_length=1000)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
            ],
        ),
    ]

マイグレーションファイルの生成ができたので,実際にデータベースのテーブルを生成する.まずは,データベースが空である(ファイルサイズが 0 バイト,さらに,.tables コマンドで何も表示されない:つまりテーブルがまだない)ことを確認しておく.

(py39) C:\Users\lecture\Documents\django\django_comment>dir ⏎
 ドライブ C のボリューム ラベルがありません。
 ボリューム シリアル番号は E033-4666 です

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

2022/07/27  11:04    <DIR>          .
2022/07/27  11:04    <DIR>          ..
2022/07/27  10:57                77 .gitignore
2022/07/27  11:11    <DIR>          comments
2022/07/27  10:58                 0 db.sqlite3
2022/07/27  10:58    <DIR>          django_comment
2022/07/27  10:50               692 manage.py
               3 個のファイル                 769 バイト
               4 個のディレクトリ  14,286,348,288 バイトの空き領域

(py39) C:\Users\lecture\Documents\django\django_comment>sqlite3 db.sqlite3 ⏎
SQLite version 3.38.2 2022-03-26 13:51:10
Enter ".help" for usage hints.
sqlite> .tables ⏎
sqlite> .exit ⏎

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

python manage.py migrate コマンドでマイグレーションを実行する.これにより,comments モデルのテーブルだけでなく様々なテーブルが登録されていることが確認できる.

(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 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 auth.0012_alter_user_first_name_max_length... OK
  Applying comments.0001_initial... OK
  Applying sessions.0001_initial... OK

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

実際に sqlite3 を操作してテーブルが作成されたことを確認するとともに,まだデータは登録されていないことも確認しておく.なお,Laravel とは異なり,生成されるテーブル名が アプリケーション名_モデル名 の形式になっていることに注意しよう.

(py39) C:\Users\lecture\Documents\django\django_comment>dir ⏎
 ドライブ C のボリューム ラベルがありません。
 ボリューム シリアル番号は E033-4666 です

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

2022/07/27  11:22    <DIR>          .
2022/07/27  11:22    <DIR>          ..
2022/07/27  10:57                77 .gitignore
2022/07/27  11:11    <DIR>          comments
2022/07/27  11:22           135,168 db.sqlite3
2022/07/27  10:58    <DIR>          django_comment
2022/07/27  10:50               692 manage.py
               3 個のファイル             135,937 バイト
               4 個のディレクトリ  14,285,156,352 バイトの空き領域

(py39) C:\Users\lecture\Documents\django\django_comment>sqlite3 db.sqlite3 ⏎
SQLite version 3.38.2 2022-03-26 13:51:10
Enter ".help" for usage hints.
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> .schema comments_comment ⏎
CREATE TABLE IF NOT EXISTS "comments_comment" (
  "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  "title" varchar(200) NOT NULL,
  "body" varchar(1000) NOT NULL,
  "created_at" datetime NOT NULL,
  "updated_at" datetime NOT NULL
);
sqlite> select * from comments_comment; ⏎
sqlite> .exit ⏎

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

また,Django では python manage.py showmigrations によって,どのマイグレーションファイルが適用済みか(どのテーブルが作成済みか)を確認できる.次の例では全てのマイグレーションファイルが適用済みであることが確認できる.

(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>

ここで,comments に関する 0001_initial をロールバックしてテーブルを一旦削除する.

(py39) C:\Users\lecture\Documents\django\django_comment>python manage.py migrate comments zero ⏎
Operations to perform:
  Unapply all migrations: comments
Running migrations:
  Rendering model states... DONE
  Unapplying comments.0001_initial... OK

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

再度 python manage.py showmigrations コマンドで確認すると,comments の 0001_initial がロールバックされていることがわかる.

(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>

この状態で,sqlite3 でテーブルの一覧を確認すると,確かに comments_comment テーブルが削除されていることがわかる.

(py39) C:\Users\lecture\Documents\django\django_comment>sqlite3 db.sqlite3 ⏎
SQLite version 3.38.2 2022-03-26 13:51:10
Enter ".help" for usage hints.
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> .exit ⏎

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

再度マイグレーションを実行すると,まだ適用されていない comments の 0001_initial だけが処理され,comments_comment テーブルが再生成された.

(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>sqlite3 db.sqlite3 ⏎
SQLite version 3.38.2 2022-03-26 13:51:10
Enter ".help" for usage hints.
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> .exit ⏎

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

なお,マイグレーションの詳細(テーブル生成後の列の追加など)はこちらを参照してください.

目次に戻る