2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Django】makemigrationsとmigrateについて

Posted at

Djangoにて使用するmakemigrationsとmigrateコマンドについて記載します

makemigrationsとは

makemigrationsは、models.pyに記載したカラム名は、文字列型などの情報をmigrationファイルに記載します
まずmodels.pyに以下のように記載したとします

models.py
from django.db import models
class Product(models.Model):
  title = models.CharField(max_length=120)
  description = models.TextField(blank=True, null=True)
  price = models.DecimalField(decimal_places=2, max_digits=1000)
  summary = models.TextField(blank=True, null=False)
  featured = models.BooleanField(null=True)

その後にmakemigrationsを実行します

$ python manage.py makemigrations
Migrations for 'products':
  products/migrations/0001_initial.py
    - Create model Product

そうするとmigrationsディレクトリに以下に0001_initial.pyファイルが作成されます
スクリーンショット 2022-05-24 21.45.14.png
中身は以下のようになってます

0001_initial.py
# Generated by Django 4.0.4 on 2022-05-24 12:12

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Product',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.TextField()),
                ('description', models.TextField()),
                ('price', models.TextField()),
            ],
        ),
    ]

makemigrationsを行うことでDBへ登録するためにmigrationファイルを作成することができます。
DBへ登録する前に最終チェックして問題あればファイルを削除して、models.pyを修正、makemigrationsを実行すれば良いでしょう。

migrateとは

migrateは、DBにmigrationファイルに記載した内容を登録します。
実行方法は、以下です

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, products, sessions
Running migrations:
  Applying products.0001_initial... OK

ここでいうadmin, auth, contenttypes, sessionsのついては、デフォルトのsettings.pyのINSTALLED_APPSに記載していて、DBを使用するアプリケーションです。

migrateするには、makemigrationsで作成したmigrationファイルが必要です。
よって、migrationsディレクトリに存在するファイルは、基本的には消さないほうが良いでしょう。
消すタイミングとしては、DBを最初の状態に戻る場合、
DBを削除し、migrationsディレクトリ内を削除することで、
特にエラーなく、最初の状態の戻すことができます。

まとめ

Djangoを学習している駆け出しエンジニアの方でDB周りに躓く場合、
まずは

  • models.pyを修正
  • python manage.py makemigrations
  • python manage.py migrate
    上記順番で実施すればいいんだなぁってことを頭に入れておくのが良いと思います。
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?