【问题标题】:MPTT model creation fails in data migration数据迁移创建MPTT模型失败
【发布时间】:2015-10-01 23:43:19
【问题描述】:

我已经编写了一个数据迁移文件,用于为 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])

默认错误处理程序中的文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/MySQLdb/connections.py”,第 36 行 引发错误类,错误值 django.db.utils.IntegrityError: (1048, "Column 'lft' cannot be null")

【问题讨论】:

  • FWIW,相同的代码在单独调用时运行良好。

标签: django-migrations django-mptt


【解决方案1】:

您必须手动向 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...

【讨论】:

    猜你喜欢
    • 2015-08-08
    • 1970-01-01
    • 2019-10-27
    • 2023-04-07
    • 2014-08-02
    • 1970-01-01
    • 2015-08-27
    • 2017-04-23
    • 2012-01-29
    相关资源
    最近更新 更多