我在项目中改了模型后使用了继承模型;但我给出了不可为空的字段错误。我应该怎么办? 我正在使用 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需要添加一个从TypeFive
到Questions
的关系.对于数据库中可能已经存在的 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
管理员)。
关于python - 使用模型继承并遇到不可为空的字段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29756443/