django 報錯:ValueError: The database backend does not accept 0 as a value for AutoField.

crystalnsd發表於2017-08-24

錯誤原因:
在建立一個model時,其中一個欄位你用了別一個model的做為外來鍵,並且給這個外來鍵設定了一個預設值 ,而這個預設值不適用於鍵model中自動建立

再找一下報錯的指令碼:

  Applying oiarpt.0004_auto_20170822_1419... OK
  Applying oiarpt.0005_auto_20170822_1652...Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "D:\python3.6\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line

由上面的資訊可以看出在執行:Applying oiarpt.0005_auto_20170822_1652…Traceback (most recent call last):時報錯的:
開啟專案\oia_report\oiarpt\migrations 找到對應的檔案可以看到:

field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='oiarpt.Product'),

問題就出在這裡:

解決方法:
刪除0005_auto_20170822_1652.py
然後重新執行:
python manage.py makemigrations
python manage.py migrate
此時就不會報錯了

相關文章