TypeError: __init__() missing 1 required positional argument: 'on_delete' 解决办法

TypeError: __init__() missing 1 required positional argument: 'on_delete' 解决办法

 

当执行 python manage.py makemigrations 出现错误:TypeError: init() missing 1 required positional argument: ‘on_delete’

解决方案:

定义外键的时候需要加上 on_delete=;
即:contract = models.ForeignKey(Contract, on_delete=models.CASCADE)

原因如下:

django 升级到2.0之后,表与表之间关联的时候,必须要写on_delete参数,否则会报异常:
TypeError: init() missing 1 required positional argument: ‘on_delete’

 

on_delete=None, # 删除关联表中的数据时,当前表与其关联的field的行为
on_delete=models.CASCADE, # 删除关联数据,与之关联也删除
on_delete=models.DO_NOTHING, # 删除关联数据,什么也不做
on_delete=models.PROTECT, # 删除关联数据,引发错误ProtectedError
# models.ForeignKey('关联表', on_delete=models.SET_NULL, blank=True, null=True)
on_delete=models.SET_NULL, # 删除关联数据,与之关联的值设置为null(前提FK字段需要设置为可空,一对一同理)
# models.ForeignKey('关联表', on_delete=models.SET_DEFAULT, default='默认值')
on_delete=models.SET_DEFAULT, # 删除关联数据,与之关联的值设置为默认值(前提FK字段需要设置默认值,一对一同理)
on_delete=models.SET, # 删除关联数据,
a. 与之关联的值设置为指定值,设置:models.SET(值)
b. 与之关联的值设置为可执行对象的返回值,设置:models.SET(可执行对象)

由于多对多(ManyToManyField)没有 on_delete 参数,所以以上只针对外键(ForeignKey)和一对一(OneToOneField)

posted @ 2019-12-24 15:51  一只小白呀  阅读(19684)  评论(0编辑  收藏  举报