我想我会通过开发一个大型商业应用程序来娱乐一下,从而用 Django 提升我的 python 游戏。我发现需要一种共同祖先方法来进行模型继承,并尝试根据 official documentation 实现它.但是,我不断收到这个非常烦人的消息,我不知道该如何处理。
- Dj 版本: Django 1.7
- Py版本:Python 3.4.2
留言
$ python manage.py makemigrations
You are trying to add a non-nullable field 'businessentity_ptr' to business 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
模型.py
class BusinessEntity(models.Model):
title = models.CharField(max_length=180)
def __str__(self):
return self.title
class Business(BusinessEntity):
description = models.TextField(max_length=600)
claimed = models.BooleanField(default=False)
slug = models.SlugField()
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return self.description
我尝试过的(每个人都会讨厌):
- 删除数据库并重新迁移
- 为所有字段设置默认值
- 将所有字段设置为
null = True
我已经看到了解决此问题的方法,但我认为这不是一个好方法。也许外面有人更了解 Django Common Ancestors 并为我指明了正确的方向。
请您参考如下方法:
因为你的父模型是抽象的,你应该这样标记它。
class BusinessEntity(models.Model):
title = models.CharField(max_length=180)
class Meta:
abstract = True
这可以防止 Django 为它创建一个单独的表,因此需要一个 _ptr 字段从子类中指向它。相反,将为您的子类创建表以直接包含继承的字段。
