1. 程式人生 > >【Python】django報錯:TypeError: __init__() missing 1 required positional argument: 'on_delete'解決辦法

【Python】django報錯:TypeError: __init__() missing 1 required positional argument: 'on_delete'解決辦法

錯誤程式碼:

from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class Author(models.Model):
    name = models.CharField(max_length=50)
    qq = models.CharField(max_length=10)
    addr = models.TextField()
    email = models.EmailField()

    def __str__(self):
        return self.name

@python_2_unicode_compatible
class Article(models.Model):
    title = models.CharField(max_length=50)
    author = models.ForeignKey(Author)
    content = models.TextField()
    score = models.IntegerField()
    tags = models.ManyToManyField('Tag')

報錯資訊:

D:\PythonWorkstation\django\django_station\queryset>python manage.py makemigrations Traceback (most recent call last): 部分省略.....     class Article(models.Model):   File "D:\PythonWorkstation\django\django_station\queryset\blog\models.py", line 20, in Article     author = models.ForeignKey('Author') TypeError: __init__() missing 1 required positional argument: 'on_delete'

原因解讀:

在django2.0後,定義外來鍵和一對一關係的時候需要加on_delete選項,此引數為了避免兩個表裡的資料不一致問題,否則就會報錯:TypeError: __init__() missing 1 required positional argument: 'on_delete'

錯誤程式碼塊:

author = models.ForeignKey(Author)

更正後:

author = models.ForeignKey(Author,on_delete=models.CASCADE)

再次執行更正後的程式碼即正常

D:\PythonWorkstation\django\django_station\queryset>python manage.py makemigrations Migrations for 'blog':   blog\migrations\0001_initial.py     - Create model Article     - Create model Author     - Create model Tag     - Add field author to article     - Add field tags to article

對on_delete引數的說明: on_delete有CASCADE、PROTECT、SET_NULL、SET_DEFAULT、SET()五個引數: CASCADE:此值設定,是級聯刪除; PROTECT:此值設定,是會報完整性錯誤; SET_NULL:此值設定,會把外來鍵設定為null,前提是允許為null; SET_DEFAULT:此值設定,會把設定為外來鍵的預設值; SET():此值設定,會呼叫外面的值,可以是一個函式。 一般情況下使用CASCADE就可以了。