报错类型
author = models.ForeignKey(User, related_name="blog_posts") TypeError: __init__() missing 1 required positional argument: 'on_delete'
错误的代码:
from django.db import models from django.utils import timezone from django.contrib.auth.models import User class BlogArticles(models.Model): title = models.CharField(max_length = 300) author = models.ForeignKey(User, related_name="blog_posts") body = models.TextField() publish = models.DateTimeField(default= timezone.now) class Meta: ordering = ("-publish",) def __str__(self): return self.title
正确的代码:
from django.db import models from django.utils import timezone from django.contrib.auth.models import User class BlogArticles(models.Model): title = models.CharField(max_length = 300) author = models.ForeignKey(User, related_name="blog_posts",on_delete=models.PROTECT) body = models.TextField() publish = models.DateTimeField(default= timezone.now) class Meta: ordering = ("-publish",) def __str__(self): return self.title
两者的不同:
author = models.ForeignKey(User, related_name="blog_posts",on_delete=models.PROTECT)