代码:
class Entry(models.Model):
"""学到的有关某个主题的具体知识"""
topic = models.ForeignKey(Topic)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'entries'
def __str__(self):
"""返回模型的字符串表示"""
return self.text[:50] + "..."
问题:
(ll_env) I:\PythonDemo\learning_log>python manage.py makemigrations learning_log
s
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "I:\PythonDemo\learning_log\ll_env\lib\site-packages\django\core\manageme
nt\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "I:\PythonDemo\learning_log\ll_env\lib\site-packages\django\core\manageme
nt\__init__.py", line 357, in execute
django.setup()
File "I:\PythonDemo\learning_log\ll_env\lib\site-packages\django\__init__.py",
line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "I:\PythonDemo\learning_log\ll_env\lib\site-packages\django\apps\registry
.py", line 112, in populate
app_config.import_models()
File "I:\PythonDemo\learning_log\ll_env\lib\site-packages\django\apps\config.p
y", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36-32\lib\imp
ortlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "I:\PythonDemo\learning_log\learning_logs\models.py", line 14, in <module
>
class Entry(models.Model):
File "I:\PythonDemo\learning_log\learning_logs\models.py", line 16, in Entry
topic = models.ForeignKey(Topic)
TypeError: __init__() missing 1 required positional argument: 'on_delete'
出现原因:
在django2.0后,定义外键和一对一关系的时候需要加on_delete选项,此参数为了避免两个表里的数据不一致问题,不然会报错:TypeError: __init__() missing 1 required positional argument: 'on_delete'
举例说明:
topic = models.ForeignKey(Topic)
需要改成:
topic = models.ForeignKey(Topic,on_delete=models.CASCADE) --在老版本这个参数(models.CASCADE)是默认值
参数说明:
on_delete有CASCADE、PROTECT、SET_NULL、SET_DEFAULT、SET()五个可选择的值
CASCADE:此值设置,是级联删除。
PROTECT:此值设置,是会报完整性错误。
SET_NULL:此值设置,会把外键设置为null,前提是允许为null。
SET_DEFAULT:此值设置,会把设置为外键的默认值。
SET():此值设置,会调用外面的值,可以是一个函数。
一般情况下使用CASCADE就可以了。
修改意见:
topic = models.ForeignKey(Topic)改为topic = models.ForeignKey(Topic,on_delete=models.CASCADE) 就可以了