Djangoのマイグレーションをとりあえず試してみる(続き)
Djangoのマイグレーションをとりあえず試してみる
https://yk5656.hatenablog.com/entry/20210403/1617375600
の続き
アプリケーションを作成し、
$ python3 manage.py startapp app
設定ファイルに「'app.apps.AppConfig',」を追加。
$ vi hoge/settings.py
・・・ INSTALLED_APPS = [ 'app.apps.AppConfig', 'django.contrib.admin', 'django.contrib.auth', ・・・
モデルを追加。
$ vi app/models.py
from django.db import models class Book(models.Model): price = models.IntegerField() name = models.CharField(max_length=100) description = models.TextField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
マイグレーションファイルを作成。
$ python3 manage.py makemigrations Migrations for 'app': app/migrations/0001_initial.py - Create model Book
下記のファイルが作られる。
$ cat app/migrations/0001_initial.py
# Generated by Django 3.2 on 2021-05-03 03:49 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Book', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('price', models.IntegerField()), ('name', models.CharField(max_length=100)), ('description', models.TextField(null=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], ), ]
マイグレーションを実行。
$ python3 manage.py migrate
テーブルが作成されているのが確認できる。
$ sudo -u postgres psql hoge_db # \d app_book Table "public.app_book" Column | Type | Collation | Nullable | Default -------------+--------------------------+-----------+----------+-------------------------------------- id | bigint | | not null | nextval('app_book_id_seq'::regclass) price | integer | | not null | name | character varying(100) | | not null | description | text | | | created_at | timestamp with time zone | | not null | updated_at | timestamp with time zone | | not null | Indexes: "app_book_pkey" PRIMARY KEY, btree (id)