Blog Post

Django 高度な Migration 3種類を紹介


作成日 2022-12-18

目次

概要

Django 本記事では Django のマイグレーションを紹介します。

マイグレーションとは

公式サイト:https://docs.Djangoproject.com/en/4.1/topics/migrations/

Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They’re designed to be mostly automatic, but you’ll need to know when to make migrations, when to run them, and the common problems you might run into.

DBのスキーマを変更するための操作です。

マイグレーションファイルだけでは足りない?

実際にスキーマ変更後以下のコマンドで対処することは可能です。

python manage.py makemigrations
python manage.py migrate

しかし、あくまで上記でできることはスキーマ変更とデフォルト値の補完です。

実際、リレーション関係のあるエンティティの最大値最小値を取りたい、json 列にデータを追加したい等のケースはあるかと思います。

新しくテーブルを作成した時点で特定の値で埋めるなど、複雑な処理をしたい場合では上記以外のマイグレーション操作が必要です。

ではどうするか?今回3つ紹介します。

操作方法

やり方 その1:直接コマンドを叩く

直接コマンドを叩く方法です。

以下手順:

  • あらかじめ、py メソッドを用意
class CSVColumn(Model):
    ...

    def adjust_head(self):
        ...
  • ターミナルで叩きます
python manage.py shell
  • 上記でインタラプタが開いた以下を入力
from my_project.models import *
for csv in CSVColumn.objects.all():
    csv.adjust_head()

やり方 その2: Django forward と rev 関数を作成

マイグレーションファイルにて記載する方法です。

以下手順:

  • 新たにmigration ファイルを作成します (コピペ etc)
  • Run Python を以下のように実装
from Django.db import migrations, models
from my_project.models import CSVColumn


def csv_column_adjust(apps, schema_editor):

    for csv in CSVColumn.objects.all():
        csv.adjust_head()


def rev_csv_column_adjust(apps, schema_editor):
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('alpha_hatchu', '0023_xx'),
    ]

    operations = [
        ...,
        migrations.RunPython(
            csv_column_adjust,
            rev_csv_column_adjust,
        ),
    ]
  • マイグレーションを実行
python manage.py migrate

やり方 その3: Django command

python manage.py <command> というように実行できる方法です。

以下、手順:

  • アプりケーション配下に management/commands/<command>.py を作成 (<command> は任意)
  • <command>.py の中に command ファイルを作成


from django.core.management.base import BaseCommand
from alpha_hatchu.models import CSVColumn

SHARD_SPLIT = 500
THREAD_SPLIT = 30


class Command(BaseCommand):
    help = 'HStock Migration'

    def handle(self, *args, **options):
        for csv in CSVColumn.objects.all():
            csv.adjust_head()
  • 以下実行
python manage.py <command>

まとめ

本記事では 高度なマイグレーションを要する場合どのような手法があるか 3 つ紹介しました。今後、これらを使ってマイグレーションが楽になれれば幸いです。 Happy Coding!

参考文献

https://docs.Djangoproject.com/en/4.1/topics/migrations/