我之所以问这个问题,是因为我在使用MPPT模型的django-hordak时遇到了这个django.db.utils.IntegrityError: null value in column “lft” violates not-null constraint。
提供的解决方案为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具有帐户模型。如上所述,数据库上的.objects.create(**data)
raises the
IntegrityError。
提议的解决方案
建议的解决方案是直接导入模型。
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。 。我想特别了解在迁移文件中使用app_registry.get_model
导入模型的逻辑。
这是一个很好的问题,因为实际上有很大的不同。
如果导入模型,您将获得模型代码中当前定义的任何内容。但是,如果您要移动模型会怎样?您如何确保您的迁移仍能正常进行?
这就是为什么有apps.get_model
。它将根据先前迁移定义的状态为您提供“虚拟”模型。请注意,这与代码中的Model不同。除非它们是ORM API的一部分,否则它不具有您实现的任何自定义功能和行为。换句话说,主要是字段和元选项,例如ordering和co。
请注意正确的签名是apps
而不是app_registry
。请勿将其与django.apps.apps
中的应用程序注册表混淆。它也具有get_model
方法。但是,这将返回您当前代码中的模型。
我希望这种区别对您有所帮助。如果您还有其他问题,请给我评论。我很高兴扩展我的答案。
最佳-乔