18
22

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 5 years have passed since last update.

manage.py migrateをおかしな感じにやってしまった。

Last updated at Posted at 2018-05-28

1.djangoでmakemigrations -> migrate がうまくいかない。

python3 manage.py migrate
(中略)

django.db.utils.OperationalError: table "common_category" already exists

sqliteのDBで、dbファイルだけコピってmigrationsのファイルをなくしてしまったわけです。
その状況で新たにmakemigrationsしても「すでにテーブルが有るぞ」となってしまう。

##2.--fake [app名] オプションを使ってみる。
migrateの履歴に「ちゃんとmigrateしたよ」と偽情報を流すような感じ。

python3 manage.py migrate --fake common
Operations to perform:
  Apply all migrations: common
Running migrations:
  Applying common.0004_auto_20180528_1203... FAKED
#

showmigrationsでみてみると無事クリアできてる。

# python3 manage.py showmigrations
admin
 [X] 0001_initial
 [X] 0002_logentry_remove_auto_add
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
common
 [X] 0001_initial
 [X] 0002_auto_20180307_1640
 [X] 0003_auto_20180521_1522
 [X] 0004_auto_20180528_1203
contenttypes
 [X] 0001_initial
 [X] 0002_remove_content_type_name
django_celery_beat
 [X] 0001_initial
 [X] 0002_auto_20161118_0346
 [X] 0003_auto_20161209_0049
 [X] 0004_auto_20170221_0000
 [X] 0005_add_solarschedule_events_choices
 [X] 0006_auto_20180210_1226

3.fakeを外したい。(SQLを再度実行したい)

# python3 manage.py showmigrations macaddr
macaddr
 [X] 0001_initial

macaddrというアプリを作成し、makemigrationsしました。
その後、python3 manage.py migrate --fake    とした状態。

python3 manage.py migrate --fake macaddr zero
というzeroオプションをつけて

macaddr [X] 0001_initial
↑のチェックを外します

 python3 manage.py migrate --fake macaddr zero
Operations to perform:
  Unapply all migrations: macaddr
Running migrations:
  Rendering model states... DONE
  Unapplying macaddr.0001_initial... FAKED
# python3 manage.py showmigrations macaddr
macaddr
 [ ] 0001_initial

チェックがはずれました。
migrateします。

# python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, common, contenttypes, django_celery_beat, macaddr, sessions, sites
Running migrations:
  Applying macaddr.0001_initial... OK

無事テーブルが作成されました。
テーブル消したりしなくていいので焦らないでやること。

18
22
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
18
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?