使用模型继承并遇到不可为空的字段错误

Using model inheritance and encounting by non-nullable field error

我在项目中改了模型后使用了继承模型;但我给出了不可为空的字段错误。我应该怎么办? 我正在使用 Django 1.7

class Questions(models.Model):
    question_category = models.ForeignKey(Course, blank=False)
    question_author = models.ForeignKey(Author, blank=False)
    question_details = models.CharField(max_length=100, blank=False, default='')
    timestamp = models.DateTimeField(auto_now_add=True)

class TypeFive(Questions):
    question_title = models.CharField(max_length=100, blank=False, default=generator(5), unique=True, editable=False)

    def __str__(self):
        return "{}".format(self.question_title)


class TypeFiveChoice(models.Model):
    question_choice = models.ForeignKey(TypeFive)
    is_it_question = models.BooleanField(default=False)
    word = models.CharField(default='', blank=False, max_length=20)
    translate = models.CharField(default='', blank=False, max_length=20)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "{} : {}, {}".format(self.question_choice, self.word, self.translate)

迁移后:

You are trying to add a non-nullable field 'questions_ptr' to typefive 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)
 2) Quit, and let me add a default in models.py

为了继承TypeFive中的Questions,Django需要添加一个从TypeFiveQuestions的关系。对于 TypeFive 中可能已经存在于数据库中的所有记录。

Django 现在不知道它应该 TopFive 与哪个问题相关。这就是 migrate 命令要求您执行的操作。您有几个选择,但它们在很大程度上取决于您的用例以及您是否处于早期开发阶段,或者是否存在此迁移必须稍后 运行 的生产数据库。

I'm in early development and running it on localhost, so iI don't care about my records. Now, what should I do?

在这种情况下,当 migrate 要求您键入 1 然后按 enter 时,您不必担心太多。现在添加数据库中 Questions 实例的 primary key,然后再次点击 enter

Django 现在将数据库中当前存在的所有 TypeFive 实例与此问题相关联,因此您可能必须在之后清理它(例如,通过在 Django 管理中编辑 TypeFive)。

@Nick Brady 在上面的问题中指出了这一点,所以我并不是要功劳,但我想强调一下。

如果您的新继承 class 仅用于被继承的目的,您可以通过将父 class 设置为抽象来轻松解决此问题。

class Parent(models.model):
    Name = models.CharField(max_length=50)

    class Meta:
        abstract = True


class Child(Parent):
    foobar = models.CharField(max_length=50)

    class Meta:
        db_table = "typenex_taxonomy_nodes"