Django模型:共同祖先继承&移民

时间:2014-11-06 12:58:28

标签: python django inheritance django-models

我认为我会通过开发一个大型商业应用程序来开发一些有趣的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

Models.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

我尝试过的事(每个人都讨厌):

  1. 删除数据库&重新迁移
  2. 为所有字段设置默认值
  3. 将所有字段设置为null = True
  4. 我已经看到了这方面的黑客,但我不认为这是一个很好的方法。也许有人会更好地理解Django Common Ancestors并指出我正确的方向。

1 个答案:

答案 0 :(得分:6)

由于您的父模型是抽象的,您应该将其标记为。

class BusinessEntity(models.Model):
    title = models.CharField(max_length=180)

    class Meta:
        abstract = True

这可以防止Django为它创建一个单独的表,因此需要_ptr字段从子类指向它。相反,将创建子类的表以直接包含继承的字段。