错误代码:
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Author(models.Model):
name = models.CharField(max_length=50)
qq = models.CharField(max_length=10)
addr = models.TextField()
email = models.EmailField()
def __str__(self):
return self.name
@python_2_unicode_compatible
class Article(models.Model):
title = models.CharField(max_length=50)
author = models.ForeignKey(Author)
content = models.TextField()
score = models.IntegerField()
tags = models.ManyToManyField('Tag')
报错信息:
D:\PythonWorkstation\django\django_station\queryset>python manage.py makemigrations
Traceback (most recent call last):
部分省略.....
class Article(models.Model):
File "D:\PythonWorkstation\django\django_station\queryset\blog\models.py", line 20, in Article
author = models.ForeignKey('Author')
TypeError: __init__() missing 1 required positional argument: 'on_delete'
原因解读:
在django2.0后,定义外键和一对一关系的时候需要加on_delete选项,此参数为了避免两个表里的数据不一致问题,否则就会报错:TypeError: __init__() missing 1 required positional argument: 'on_delete'
错误代码块:
author = models.ForeignKey(Author)
更正后:
author = models.ForeignKey(Author,on_delete=models.CASCADE)
再次执行更正后的代码即正常
D:\PythonWorkstation\django\django_station\queryset>python manage.py makemigrations
Migrations for 'blog':
blog\migrations\0001_initial.py
- Create model Article
- Create model Author
- Create model Tag
- Add field author to article
- Add field tags to article
对on_delete参数的说明:
on_delete有CASCADE、PROTECT、SET_NULL、SET_DEFAULT、SET()五个参数:
CASCADE:此值设置,是级联删除;
PROTECT:此值设置,是会报完整性错误;
SET_NULL:此值设置,会把外键设置为null,前提是允许为null;
SET_DEFAULT:此值设置,会把设置为外键的默认值;
SET():此值设置,会调用外面的值,可以是一个函数。
一般情况下使用CASCADE就可以了。