TypeError: __init__() missing 1 required positional argument: 'on_delete'
Django 中创建Model时报以下错误:
TypeError: init() missing 1 required positional argument: ‘on_delete’
E:\dproject\project>python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "E:\Python37\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "E:\Python37\lib\site-packages\django\core\management\__init__.py", line 377, in execute
django.setup()
File "E:\Python37\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "E:\Python37\lib\site-packages\django\apps\registry.py", line 114, in populate
app_config.import_models()
File "E:\Python37\lib\site-packages\django\apps\config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "E:\Python37\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "E:\dproject\project\myApp\models.py", line 11, in <module>
class Students(models.Model):
File "E:\dproject\project\myApp\models.py", line 18, in Students
sgrade = models.ForeignKey("Grades")
TypeError: __init__() missing 1 required positional argument: 'on_delete'
在django2.0后,定义外键和一对一关系的时候需要加on_delete选项,此参数为了避免两个表里的数据不一致问题,不然会报错
例:
# 关联外键 sgrade = models.ForeignKey("Grades")
改成:
# 关联外键 sgrade = models.ForeignKey("Grades", on_delete=models.CASCADE)
参数说明:
on_delete有CASCADE、PROTECT、SET_NULL、SET_DEFAULT、SET()五个可选择的值
CASCADE:此值设置,是级联删除。
PROTECT:此值设置,是会报完整性错误。
SET_NULL:此值设置,会把外键设置为null,前提是允许为null。
SET_DEFAULT:此值设置,会把设置为外键的默认值。
SET():此值设置,会调用外面的值,可以是一个函数。
一般情况下使用CASCADE就可以了。
由于多对多(ManyToManyField)没有 on_delete 参数,所以以上只针对外键(ForeignKey)和一对一(OneToOneField)