Search code examples
django-migrationsdjango-mptt

MPTT model creation fails in data migration


I have written a data migration file for creating some initial data for a MPTT model.

But the creation fails,

def create_foo(apps, schema_editor):
    db_alias = schema_editor.connection.alias
    logger = logging.getLogger(__name__)

    Foo = apps.get_model("app", "Foo")

    for attr in ROLES:
        try:
            foo = Foo.objects.using(db_alias).get(name=attr[0])
    except Foo.DoesNotExist:
        parent = Foo.objects.using(db_alias).get(name=attr[1]) if attr[1] else None
        if parent:
            foo = Foo.objects.create(name=attr[0], parent=parent)
        else:
            foo = Foo.objects.using(db_alias).create(name=attr[0])
        logger.info("Created foo - %s" % foo)

I am getting below error while executing below line, any ideas?

foo = Foo.objects.using(db_alias).create(name=attr[0])

File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorclass, errorvalue django.db.utils.IntegrityError: (1048, "Column 'lft' cannot be null")


Solution

  • You have to manually register model with mptt:

    from mptt import register
    
    def create_foo(apps, schema_editor):
        db_alias = schema_editor.connection.alias
        logger = logging.getLogger(__name__)
    
        Foo = apps.get_model("app", "Foo")
        register(Foo)
    
        # ... rest of your code...