1
0

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】defaultの未設定によるmigrateエラーの対処について

Last updated at Posted at 2023-05-29

何が起きたか

既にmakemigrationsとmigrateを行い、DBにデータを格納した後に新しいフィールドを追加したところmigrateエラーが発生しました。

エラー内容

It is impossible to add a non-nullable field 'xxxx' to postproject without specifying a default. This is because the database needs something to populate existing rows.
Please select a fix:

 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)

 2) Quit and manually define a default value in models.py.

Select an option:

上記のようなエラーが発生。
内容としては…
デフォルト値を設定せずに既存フィールドにxxxを追加することはできないよ。追加したければデフォルトの値を設定してね
ということらしい。

対処方法

コンソールに表示された対処方法は2つ
その1:今デフォルト値を入力してね
その2:makemigrationsするのやめてmodels.pyにデフォルト値を入力して再度試してね
です。

ちなみに、もう1つ対処方法があり、DBとmigrationsファイルを削除し再度クリエイトする方法があります。
こちらの方法は今回必要ないので行いません。

今回は、2番のmakemigrationsを中断し、models.pyにデフォルト値を入力する方法を行います

対象となるモデルにデフォルト値をあたえます。

text = models.CharFields(max_length=50, blank=True, null=True) 

或いは

text = models.CharFields(max_length=50, default='') 

とします。
変更内容を保存し、再度makemigrationsを行ういます。

Migrations for 'xxxxx':
  xxxxx\migrations\0003_testproject_text.py
    - Add field text to testproject

無事makemigratinsが完了しました。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?