python - “makemigrations”要求使用非抽象模型继承的默认值

标签 python django inheritance model makemigrations

我正在尝试一个简单的模型继承:

class Product(models.Model):
    creation_date = models.DateTimeField(auto_now_add=True)

class Application(Product):
    name = models.CharField(max_length=200)

“makemigrations”要求默认值:

You are trying to add a non-nullable field 'product_ptr' to application without a default; we can't do that (the database needs something to populate existing rows).

我看到了here我可以使用 Meta 类生成一个抽象模型,但我不能这样做,因为我在其他模型中专门将其引用为实际模型:

class Comment(models.Model):
    product      = models.ForeignKey('Product', related_name="comments")

删除数据库时运行“makemigrations”也会导致同样的问题。

我能做点什么吗?

Django 1.9

最佳答案

您还没有解释您所做的更改到底是什么,您似乎已将您的 Application 模型更改为从它之前继承的 Product 继承模型.模型.这会导致 django 在幕后创建 1 对 1 映射。自己没有添加到模型中的product_ptr的添加进入图片

引用:https://docs.djangoproject.com/en/1.9/topics/db/models/#multi-table-inheritance

The inheritance relationship introduces links between the child model and each of its parents (via an automatically-created OneToOneField).

在迁移过程中将此字段添加到包含数据的表中有点棘手,因为此字段需要是唯一的。如果您只是创建一个名为 Application 的新模型,则值 1 就可以了。

关于python - “makemigrations”要求使用非抽象模型继承的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37856747/

相关文章:

c++ - 在派生中取消隐藏与基类具有相同名称和不同签名的某些函数

python - mysql数据库优先级顺序

python - PyQt:当自定义 QAbstractListModel 数据更改时如何更改 QComboBox 中的 currentIndex

python - 在 Django 中提供动态生成的 ZIP 文件

python - 通过猴子修补覆盖方法

python - 在 Python 3 中扩展一个类并使用 __init__ 构造它

python - Heroku & Django : "OSError: No such file or directory: '/app/{myappname}/static'"

python - 如何生成一个不以 0 开头且具有唯一数字的随机 4 位数字?

django - 通过相关对象链接查询

python - Django 管理员。从 list_display 编辑用户个人资料的链接