我将这些字段添加到我的模型中:
class WatchList(models.Model):
name = models.CharField(max_length=20)
class Thing(models.Model):
watchlist = models.ForeignKey(WatchList)
成功运行schemamigration:
>>> $ python2.7 manage.py schemamigration myapp --auto
+ Added model myapp.WatchList
? The field 'Thing.watchlist' does not have a default specified, yet is NOT NULL.
? Since you are adding this field, you MUST specify a default
? value to use for existing rows. Would you like to:
? 1. Quit now, and add a default to the field in models.py
? 2. Specify a one-off value to use for existing columns now
? Please select a choice: 2
? Please enter Python code for your one-off default value.
? The datetime module is available, so you can do e.g. datetime.date.today()
>>> 0
+ Added field watchlist on myapp.Thing
Created 0004_auto__add_watchlist__add_field_thing_watchlist.py. You can now apply this migration with: ./manage.py migrate myapp
在尝试这样做之前我没有遇到任何问题,但出于某种原因我收到了以下错误:
>>> $ python2.7 manage.py migrate myapp
FATAL ERROR - The following SQL query failed: ALTER TABLE "myapp_thing" ADD CONSTRAINT "watchlist_id_refs_id_1b2eef756112b8e" FOREIGN KEY ("watchlist_id") REFERENCES "myapp_watchlist" ("id") DEFERRABLE INITIALLY DEFERRED;
The error was: insert or update on table "myapp_thing" violates foreign key constraint "watchlist_id_refs_id_1b2eef756112b8e"
DETAIL: Key (watchlist_id)=(0) is not present in table "myapp_watchlist".
如何成功将更改迁移到模型?感谢任何可能有用的想法!
答案 0 :(得分:4)
这是因为您在迁移中指定了0
作为默认值。删除迁移并再次运行,这次指定一个空字符串作为默认值。
如果您已经在数据库中有一些数据,则需要在ForeignKey中指定null=True
和blank=True
,否则它将会中断。