2013-10-16 28 views
2

我添加了這些領域我的模型:Django的南方遷移錯誤:項不存在

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". 

我怎樣才能成功遷移改變模型S'感謝任何可能有所幫助的想法!

回答

4

這是因爲您指定0作爲遷移中的默認值。刪除遷移並再次運行,這次指定一個空字符串作爲默認值。

如果你已經在數據庫中有一些數據,你需要在ForeignKey中指定null=Trueblank=True,否則它會中斷。

+0

好的,謝謝你的想法。我這樣做了,這次輸入''''作爲默認值。但是,這次收到了一個不同的錯誤:'django.db.utils.DatabaseError:column「none」does not exist'。我錯過了什麼嗎?感謝您的想法! –

+0

好的,請看我的編輯。如果這不起作用,你至少應該從錯誤信息中獲得更多線索。 –

+0

不好意思,嗯,不幸的是,也沒有工作。該錯誤只說:'django.db.utils.DatabaseError:列「無」不存在'。任何其他想法可能有幫助?感謝您的任何想法! –