数据迁移时创建MPTT模型失败

MPTT model creation fails in data migration

我已经编写了一个数据迁移文件,用于为 MPTT 模型创建一些初始数据。

但是创建失败,

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)

我在执行下面的代码时遇到错误,有什么想法吗?

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")

您必须使用 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...