Reputation: 9289
I added these fields to my model:
class WatchList(models.Model):
name = models.CharField(max_length=20)
class Thing(models.Model):
watchlist = models.ForeignKey(WatchList)
Ran the schemamigration successfully:
>>> $ 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
I haven't had a problem before trying to do this, but for some reason I received the following error:
>>> $ 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".
How can I successfully migrate the changes to the models? Thanks for any ideas that might help!
Upvotes: 4
Views: 3652
Reputation: 3125
It's because you specified 0
as the default value in the migration. Delete the migration and run it again, this time specify an empty string as the default.
If you already have some data in the database you'll need to specify null=True
and blank=True
in the ForeignKey or it'll break.
Upvotes: 5