django_migrations
はマイグレーション履歴を保持するテーブル。
しかし、意外とドキュメントに説明はない。 主にチュートリアル part 2 に以下の説明がある通りである。
Django tracks which ones are applied using a special table in your database called django_migrations
django
リポジトリを検索し、チュートリアル part2を含めて記載箇所は以下の3箇所のようだった。
コードの配置場所
django/db/migrations/recorder.py
にdjango_migrations
のコードが存在している。
https://github.com/django/django/blob/main/django/db/migrations/recorder.py
If a migration is unapplied its row is removed from the table. Having a row in the table always means a migration is applied.
とあり、マイグレーションの適用状態をテーブルに記録していることがわかる。
MigrationRecorder
クラスのMigration
メソッド内部にMigration
クラスがあり、そこでModelの定義がされている。
メソッド内部にクラスがある書き方は見慣れなかったが、docstringにはAppRegistryNotReady
を防ぐための遅延ロードの手法であることが書かれていた。
Lazy load to avoid AppRegistryNotReady if installed apps import MigrationRecorder.
モデルの記録内容
記録する内容は以下の3つ。
具体例を見ると、以下のようになっていた。
postgres=# SELECT * FROM django_migrations WHERE app='tasks'; id | app | name | applied ----+-------+------------------------------------+------------------------------- 19 | tasks | 0001_initial | 2024-04-06 04:44:41.661527+00 20 | tasks | 0002_task_title_alter_task_content | 2024-04-06 04:44:41.671349+00 21 | tasks | 0003_task_limit_date | 2024-04-06 04:44:41.677108+00 22 | tasks | 0004_task_status | 2024-04-06 04:44:41.682666+00 23 | tasks | 0005_task_order | 2024-04-06 04:44:41.687782+00 24 | tasks | 0006_alter_task_status | 2024-04-06 04:44:41.692116+00 (6 rows)
その他のメソッド
そのほか、以下が定義されていた。
migration_qs
has_table
ensure_schema
applied_migrations
record_applied
record_unapplied
flush
この中のrecord_applied
によって、マイグレーション適用時の記録が書き込こまれ、record_unapplied
によってマイグレーションがロールバックなど、適用されなくなったときには削除されているようだった。
雑談
今までと文体が変わったが、この書き方の方が調べ物をしたときはスムーズだったので、試しに公開してみた。 このまま継続する...かもしれないし、継続しないかもしれない。 自己学習の記録であることを考えると、このままなのかな、という気はしている。