【问题标题】:Django Models: Common Ancestor Inheritance & MigrationDjango 模型:共同祖先继承和迁移
【发布时间】:2015-01-02 23:55:08
【问题描述】:

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

我已经看到了一个 hack,但我认为这不是一个好方法。也许有人更了解 Django Common Ancestors,并为我指明了正确的方向。

【问题讨论】:

  • 您是否需要 BusinessEntity 成为您可以查询的实际具体模型?否则作为抽象模型会更好,你的问题就不会发生。
  • 模型的Django继承可能会变得混乱(即使使用mixin而不是具体的祖先)。我很遗憾在我当前的项目中使用了它。我发现很多极端情况POLA被违反了。
  • @DanielRoseman 是的,这只是抽象的。无需查询 BusinessEntity 对象。

标签: python django inheritance django-models


【解决方案1】:

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

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

    class Meta:
        abstract = True

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

【讨论】:

    猜你喜欢
    • 2016-10-08
    • 2021-10-30
    • 2019-03-28
    • 1970-01-01
    • 2016-01-04
    • 1970-01-01
    • 2012-02-08
    • 2011-06-29
    • 2010-11-08
    相关资源
    最近更新 更多