LoginSignup
1
1

More than 1 year has passed since last update.

Djangoで既存テーブルにForeignKeyを追加する

Posted at

Djangoで、既存テーブルにForeignKeyを追加する

もともと、Userモデルが存在していて、そこに以下のようにStatusモデルを追加します。

models.py
class User(Model):
    id = UUIDField(primary_key=True)
    name = TextField()
models.py
class Status(Model):
    id = UUIDField(primary_key=True)
    name = TextField(primary_key=True)

class User(Model):
    id = UUIDField(primary_key=True)
    status = ForeignKey(Status)
    name = TextField()

makemigrationsを実行すると以下のメッセージが出力されます。

You are trying to add a non-nullable field 'status' to user without a default; we can't do that (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)
 2) Quit, and let me add a default in models.py

外部キー制約をつけたので、nullを許容したくないのですが、既存のカラムになにかデータを入れる必要がありました。
一時的なデフォルト値を設定するかmodels.pyを修正するかの入力を求められました。

今回の対応としては、

  1. ForeignKey(Status, null=True)
  2. 外部キーデータを投入
  3. ForeignKey(Status)に変更

の順番でそれぞれmakemigrationsを実行して、マイグレーションファイルを作成しました。

他に方法はあるのでしょうか。。。

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