MPTT模型创建在数据迁移中失败

Ela*_*i K 0 django-mptt django-migrations

我已经编写了一个数据迁移文件,用于为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)
Run Code Online (Sandbox Code Playgroud)

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

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

文件“ /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/MySQLdb/connections.py”,行36,在defaultErrorhandler中引发错误类,错误值django.db.utils.IntegrityError:( 1048,“列'lft'不能为空”

Dim*_*muR 5

您必须使用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...
Run Code Online (Sandbox Code Playgroud)