今天,在用Django做迁移模型时,执行迁移数据库python manage.py makemigrations learning_log时出现错误。原代码为:
from django.db import models
# Create your models here.在这里创建模型
class Topic(models.Model):
"""用户学习的主题"""
text = models.CharField(max_length = 200)
date_added = models.DateTimeField(auto_now_add = True)
def __str__(self):
"""返回模型的字符串表示"""
return self.text
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] + "..."
错误信息如下所示:
Traceback (most recent call last):
File "manage.py", line 15, in
execute_from_command_line(sys.argv)
--snip--
File "D:\Pythondebug\my_program\learning_log\learning_logs\models.py", line 13, in
class Entry(models.Model):
File "D:\Pythondebug\my_program\learning_log\learning_logs\models.py", line 15, in Entry
topic = models.ForeignKey(Topic)
TypeError: __init__() missing 1 required positional argument: 'on_delete'
这是因为在django2.0后,定义外键和一对一关系的时候需要加on_delete选项,此参数为了避免两个表里的数据不一致问题,不然会报错。此时将如下代码做替换修改,则问题解决。
topic = models.ForeignKey(Topic)
topic = models.ForeignKey('Topic', on_delete=models.CASCADE)