當執行 python manage.py makemigrations 出現錯誤:TypeError: init() missing 1 required positional argument: ‘on_delete’
解決方案:
定義外鍵的時候需要加上 on_delete=;
即:contract = models.ForeignKey(Contract, on_delete=models.CASCADE)
原因如下:
django 升級到2.0之后,表與表之間關聯的時候,必須要寫on_delete參數,否則會報異常:
TypeError: init() missing 1 required positional argument: ‘on_delete’
on_delete=None, # 刪除關聯表中的數據時,當前表與其關聯的field的行為 on_delete=models.CASCADE, # 刪除關聯數據,與之關聯也刪除 on_delete=models.DO_NOTHING, # 刪除關聯數據,什么也不做 on_delete=models.PROTECT, # 刪除關聯數據,引發錯誤ProtectedError # models.ForeignKey('關聯表', on_delete=models.SET_NULL, blank=True, null=True) on_delete=models.SET_NULL, # 刪除關聯數據,與之關聯的值設置為null(前提FK字段需要設置為可空,一對一同理) # models.ForeignKey('關聯表', on_delete=models.SET_DEFAULT, default='默認值') on_delete=models.SET_DEFAULT, # 刪除關聯數據,與之關聯的值設置為默認值(前提FK字段需要設置默認值,一對一同理) on_delete=models.SET, # 刪除關聯數據, a. 與之關聯的值設置為指定值,設置:models.SET(值) b. 與之關聯的值設置為可執行對象的返回值,設置:models.SET(可執行對象)
注:由於多對多(ManyToManyField)沒有 on_delete 參數,所以以上只針對外鍵(ForeignKey)和一對一(OneToOneField)