LoginSignup
0

More than 5 years have passed since last update.

django migrate時のduplicate key name

Posted at

TL;DR

SQLが得意な人は読んでも当たり前のことが書いてあります。
djangoでmigrationファイルを作成して、migrateする時にエラーに遭遇したので解決策を探しました。

免責的ですが、djangoによる根本的な解決策にはなっていません。
(私の調査では、問題に対する対症療法しか見つけられてないです。)

本質的には、このエラーが起こらないために、
どうしたほうがいいのかを考えるべきなのですが、まだ考えがまとまっていません。
たとえば、インデックスを付与するタイミングであるとかフローとか不明な点が多いです。

今回のエントリーについては、エラーに対してSQLで強引に解決したのでバッドプラクティスだと思います。

問題設定

> python manage.py migrate
....
....
django.db.utils.OperationalError: (1061, "Duplicate key name 'xxxx'")

これだけで伝わる人はそれほど多くないかもしれません。
簡単に意訳すると、

djangoでDBを操作しようとしたけど、xxxっていう重複したキーのせいでエラー起きてるよ

って言ってます。
djangoに限らず、調べた限りではrailsでも同じような問題を探索してる人がいました。
コミュニティの大きさと多様性の重要性が身にしみてわかります。詳しくは、リファレンス

解き方

StackOverFlowやProgressのエントリーによると、

  • I just ran in to this error and I was able to solve it by dropping the index named in the error. (Stack Over Flow)

  • Recreate the index by first dropping the index and creating it back again (Progress)

要は、
「インデックス落としてもう一回作れ」
ってことみたい。つまり、SQLに翻訳するなら

> DROP INDEX key_name ON table_name 

をしろとのこと。

他にも、--fake使ってやる人もStackOverFlowにはいたみたいだけど、
この人自身があんまりいいやり方じゃないって言ってますね。
複数ソースを見た感じ、これが共通の今の僕に探せるベターな解決策でした。

おまけ

--fakeってなんだっけ? 
答) manage.py migrateの引数です。

そういうことではないよね笑
django公式によると

--fake
Marks the migrations up to the target one (following the rules above) as applied, but without actually running the SQL to change your database schema.

This is intended for advanced users to manipulate the current migration state directly if they're manually applying changes; be warned that using --fake runs the risk of putting the migration state table into a state where manual recovery will be needed to make migrations run correctly.

意訳するなら

このコマンドを使うと、変更したいターゲットのテーブルなどに対して、マイグレーションが適用されたことにする。しかし、実際にはデータベースを変更するクエリは実行されない。
この操作は、SQL操作に長けたユーザーが使うことを想定している。例えば、彼らが手動でDBを変更している場合に、現在のマイグレーションを直接操作するケースとか。
ただ、--fakeを使うことのリスクにはリスクがある。具体的には、正しくマイグレーションするために、今までのマイグレーションの状態を手動で元に戻さなくてはならない状態に陥る可能性である。

って感じだろうか。どちらにしても僕は、advanced userではないから厄介になることはなさそうです。

Reference

本編

  1. https://stackoverflow.com/questions/34598177/django-database-migration-error-duplicate-key
  2. https://knowledgebase.progress.com/articles/Article/000048785
  3. http://d.hatena.ne.jp/japanrock_pg/20110225/1298623790
  4. https://dev.mysql.com/doc/refman/8.0/en/drop-index.html

おまけ

  1. https://www.ganbaruyo.net/details/django-migration-error/
  2. http://nissy0409.hatenablog.com/entry/2015/09/22/061147
  3. https://docs.djangoproject.com/ja/2.1/ref/django-admin/#migrate

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
0