2016-06-20 15 views
0

在試圖運行manage.py makemigrations,我收到以下錯誤:在我的models.py中,一個ForeignKey聲明不需要默認值,但另一個呢?爲什麼?

You are trying to add a non-nullable field 'menu_category' to fooditem without 
a default; we can't do that (the database needs something to populate existing 
rows. 

我的代碼如下:

models.py

class FoodItem(models.model): 
    restaurant = models.ForeignKey('Restaurant', on_delete=models.CASCADE) 
    menu_category = models.ForeignKey('MenuCategory', on_delete=models.CASCADE) 
    ... 

是沒有任何意義的是部分當我刪除menu_category行時,不會發生任何錯誤,儘管餐館外鍵也沒有默認值。另外,如果我必須指定一個外鍵的默認值,我甚至會指定什麼值?

+0

你必須與現有值的DB行因此,Django預計新的默認值。由於該屬性的現有值,您只會看到此錯誤;否則你可以在沒有默認的情況下正確定義你的外鍵。 – Ivan

+0

有什麼辦法可以擺脫現有的價值?另外,我不知道我是如何能夠看到現有的價值觀,因爲我剛剛創建了這個領域;我從來沒有遷移過它。 –

+0

現有的「值」很可能爲空,但它們在技術上仍佔用您桌子中的空間。如果不會導致過多的返工,您可能會完全刪除違規行。 – Ivan

回答

1

您只添加一個名爲menu_category的新列,對不對? restaurant字段不會給出錯誤,因爲它已經存在。

Django爲您提供此錯誤,因爲您正在添加一個字段,該字段對於已存在且沒有默認值的表不能爲空。您可能需要允許空值(所以創建的列值可以在已存在的行中爲空)或指定默認值以填充列。

Django應該詢問您是否要爲該模塊提供「一次性」默認值。如果您有一些FoodItem對象可以擁有的「默認」菜單類別,則在django提示您輸入值時指定其ID。

例prmopt: 「menu_category」

$ python manage.py makemigrations 
You are trying to add a non-nullable field 'menu_category' to fooditem 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 
Select an option: 1 
Please enter the default value now, as valid Python 
The datetime module is available, so you can do e.g. datetime.date.today() 
>>> 1 
Migrations for 'my_app': 
    0002_fooditem_menu_category.py: 
    - Add field menu_category to fooditem 
+0

我會提供的默認值會自動解釋爲外鍵的ID?如果我輸入一個字符串會發生什麼? –

+0

是的,這是外鍵標識。如果您指定了字符串,則在應用遷移時會出現錯誤。您始終可以手動編輯遷移以修復任何錯誤並重試。 – Anonymous

相關問題