在我的models.py文件中添加了author字段之后,我试图进行迁移,但是Django问我这个问题:
You are trying to add a non-nullable field 'author' to entry without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
我的Models.py文件:
from django.db import models
from django.utils import timezone
from django.urls import reverse
from django.contrib.auth.models import User
class Entry(models.Model):
title = models.CharField(max_length=50, default=timezone.now)
date = models.DateTimeField(default=timezone.now)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
def get_absolute_url(self):
return reverse('diary:index')
def __str__(self):
return self.title
我想添加当前处于活动状态的用户作为作者,所以我在views.py文件中执行了此操作:
class EntryCreate(CreateView):
model = Entry
fields = ['title', 'content']
def form_valid(self, form):
form.instance.author = self.request.author
return super().form_valid(form)
我应该怎么做才能避免这种情况?
预先感谢!
答案 0 :(得分:1)
向您的作者添加default=None
答案 1 :(得分:-1)
这可能是由于您的项目中已有迁移。如果您不介意删除一些以前的迁移,我建议您删除创建 Author 模型的迁移以及以下所有迁移。删除本地数据库后,可以进行makemigrations和migrate,无需设置默认值。
显然,如果您不想删除数据库或确实想删除迁移,这种方法是不可行的。