【发布时间】:2019-12-02 16:06:49
【问题描述】:
我问这个问题是因为我在使用 django-hordak 时遇到了这个django.db.utils.IntegrityError: null value in column “lft” violates not-null constraint,它使用了 MPPT 模型。
提出的一些解决方案是hacky,因为它们违反了常规做法,但它们确实有效。
基础知识
在 django 中编写自定义迁移时,例如创建基线数据时。
def forward_func(apps_registry, schema_editor):
Model = apps_registry.get_model('app_name', 'ModelName')
Model.objects.create(**{'field_1': 'field_1', 'field_2': 'field_2')
# Do whatever you want with my Model
在我的情况下,django-hordak 使用帐户模型。上面指定的 DB 上的 .objects.create(**data)
raises theIntegrityError。
建议的解决方案
提出的解决方案之一是直接导入模型。
def forward_func(apps_registry, schema_editor):
# Model = apps_registry.get_model('app_name', 'ModelName')
# lets forget about importing the standard way because it will raise integrity error.
from app_name.models import ModelName as Model
# Now we can proceed to deal with our model without Integrity Error.
Model.objects.create(**data)
这让我害怕直接在迁移文件中导入模型可能产生的不良副作用。
因为在迁移文件中没有以这种方式导入模型一定有很好的理由。
我不是在寻找 MPTT 模型在导入标准方式时失败的原因,因为该问题有一个 answer here。 .
我特别想了解在迁移文件中使用apps.get_model 导入模型背后的逻辑。
【问题讨论】:
-
见full explanation。 TL;DR:注册表包含创建迁移时模型的冻结版本,这可能与现在完全不同。
-
感谢@Daniel Roseman,查看了文档。如果你能写出被接受的答案。会有帮助的。
标签: django import django-migrations