本文介绍了MPTT模型创建在数据迁移中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经编写了一个数据迁移文件,用于为MPTT模型创建一些初始数据.
I have written a data migration file for creating some initial data for a MPTT model.
但是创建失败,
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])
推荐答案
您必须手动向mptt注册模型:
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...
这篇关于MPTT模型创建在数据迁移中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!