【问题标题】:Django Error: "You are trying to add a non-nullable field 'author' to entry without a default"Django 错误:“您正在尝试将不可为空的字段‘作者’添加到没有默认值的条目中”
【发布时间】:2019-10-06 16:03:31
【问题描述】:

在我的 models.py 文件中添加作者字段后,我试图进行迁移,但 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)

我应该怎么做才能避免这种情况?

提前致谢!

【问题讨论】:

    标签: python django model


    【解决方案1】:

    为您的作者添加default=None

    【讨论】:

    【解决方案2】:

    这可能是由于您在项目中已有的迁移。如果您不介意删除一些以前的迁移,我建议您删除创建作者模型的迁移以及以下所有迁移。删除本地数据库后,您可以进行makemigrations和迁移,而无需设置默认值。

    显然,如果您不想删除数据库或确实想删除迁移,这种方法是不可行的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-09
      • 2020-07-12
      • 2020-06-03
      • 2016-01-04
      • 2020-03-28
      • 2015-09-30
      • 2021-09-06
      • 1970-01-01
      相关资源
      最近更新 更多