Django2.0在根据models生成数据库表时报 __init__() missing 1 required positional argument: 'on_delete'

时间:2021-11-07 18:06:23

1、产生原因:在创建外键后,执行 python manage.py makemigrations报错,具体代码为:

from django.db import models

class Classes(models.Model):
   
    title = models.CharField(max_length=32)
    m = models.ManyToManyField("Teachers")

class Teachers(models.Model):

    name = models.CharField(max_length=32)

class Student(models.Model):
    username = models.CharField(max_length=32)
    age = models.IntegerField()
    gender = models.BooleanField()
    cs =  models.ForeignKey("Classes")

2、终端上显示报错为:

D:\pythonstudy\Django_demo>python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\huiYan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "C:\Users\huiYan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 347, in execute
    django.setup()
  File "C:\Users\huiYan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\huiYan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 112, in populate
    app_config.import_models()
  File "C:\Users\huiYan\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "C:\Users\huiYan\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
  File "D:\pythonstudy\Django_demo\app01\models.py", line 18, in <module>
    class Student(models.Model):
  File "D:\pythonstudy\Django_demo\app01\models.py", line 22, in Student
    cs = models.ForeignKey("Classes")
TypeError: __init__() missing 1 required positional argument: 'on_delete'

3、解决方法:

      在外键上后面添加on_delete=models.CASCADE,错误消失。

  cs = models.ForeignKey("Classes",on_delete=models.CASCADE,)