何が起きたか
既に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が完了しました。