跟着《跟老齐学python:django实战》学习Django web开发,先写好如下代码,保存为C:\work\mysite\blog\models.py
1 from django.db import models 2 3 # Create your models here. 4 5 from django.utils import timezone 6 from django.contrib.auth.models import User 7 8 class BlogArticles(models.Model): 9 title = models.CharField(max_length=300) 10 author = models.ForeignKey(User, related_name="blog_posts") 11 body = models.TextField() 12 publish = models.DateTimeField(default=timezone.now) 13 14 class Meta: 15 ordering = ("-publish",) 16 17 def _str_(self): 18 return self.title
然后运行python manage.py makemigrations,
出现以下错误:TypeError: __init__() missing 1 required positional argument: 'on_delete',并指明了错误在10行。
查资料,发现是书上的django版本和自己机器版本不一致造成,我的版本是Django2.0.7.
解决方法如下:
修改10行代码为:
author = models.ForeignKey(User, related_name="blog_posts",on_delete=models.CASCADE)
再运行python manage.py makemigrations,成功运行,并在blog/migrations 目录中创建了一个BlogArticles 模型。
。