【问题标题】:Using model inheritance and encounting by non-nullable field error使用模型继承和非可空字段错误计数
【发布时间】:2015-06-27 16:24:27
【问题描述】:

更改模型后,我在项目中使用了继承模型;但我给出了不可为空的字段错误。我该怎么办? 我使用的是 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 命令所要求的。您有几个选项,但它们在很大程度上取决于您的用例以及您是否处于早期开发阶段,或者是否有一个生产数据库必须稍后运行此迁移。
  • 我处于早期开发阶段并在本地主机上运行它,所以我不关心我的记录。现在,我该怎么办?

标签: python django inheritance python-3.x django-models


【解决方案1】:

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

Django 现在不知道应该将TopFive 与哪个问题联系起来。这就是 migrate 命令所要求的。您有几个选项,但它们在很大程度上取决于您的用例以及您是否处于早期开发阶段,或者是否有生产数据库需要稍后运行此迁移。

我处于早期开发阶段并在本地主机上运行它,所以我不在乎 关于我的记录。现在,我该怎么办?

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

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

【讨论】:

  • 但是如果 Questions 表没有退出呢?
  • 我找到了这篇文章,它对我正在寻找的东西很有帮助。如果您尝试抽象您的类。在子类 Meta 中设置 abstract = True:链接:stackoverflow.com/questions/26780098/…
【解决方案2】:

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

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

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"

【讨论】:

    猜你喜欢
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多