models.py中建表代码如下
class Student(models.Model):
……
grade = models.ForeignKey('grade')
执行数据库迁移语句
python manage.py makemigrations
报错如下:
File "E:\work\test\Students\myApp\models.py", line 12, in <module>
class Student(models.Model):
File "E:\work\test\Students\myApp\models.py", line 18, in Student
grade = models.ForeignKey('grade')
TypeError: __init__() missing 1 required positional argument: 'on_delete'
修改如下:
class Student(models.Model):
……
grade = models.ForeignKey('grade',on_delete=models.CASCADE)
再次执行迁移语句,成功!
(base) E:\work\test\Students>python manage.py makemigrations
Migrations for 'myApp':
myApp\migrations\0001_initial.py
- Create model Grade
- Create model Student
这是因为在django2.0后,定义外键和一对一关系的时候需要加on_delete选项,此参数为了避免两个表里的数据不一致问题,不然会报错。此时将如下代码做替换修改,则问题解决。