I am asking this question because I ran into this django.db.utils.IntegrityError: null value in column “lft” violates not-null constraint when I was using django-hordak which uses MPPT models.
Some of the solutions proposed are hacky
as they go against common practice but they work.
THE BASICS
In django when writing custom migrations for example when creating baseline data.
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
In my situation django-hordak with the account model. That .objects.create(**data)
raises the
IntegrityError on the DB as specified above.
Proposed solution
One of the solutions proposed solution is to import the model directly.
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)
This leaves me scared of possible undesirable side effects of importing models directly in migrations files.
As there must be very good reasons why the model is not imported that way in the migration files.
I am not looking for the reason why MPTT models fail when imported the standard way as that question has an answer here. .
I want to understand particularly the logic behind importing models using apps.get_model
in migration files.