django-mptt引发django.db.utils.IntegrityError:列"lft"中的空值.违反非空约束 [英] django-mptt raises django.db.utils.IntegrityError: null value in column "lft" violates not-null constraint

查看:131
本文介绍了django-mptt引发django.db.utils.IntegrityError:列"lft"中的空值.违反非空约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

条件:Django == 1.8.7иdjango-mptt == 0.8.0.

Conditions: Django==1.8.7 и django-mptt==0.8.0.

有一个模型:

class Tree(mptt_models.MPTTModel):
    name = models.CharField(max_length=120, unique=True)
    slug = models.SlugField(max_length=256, unique=True)
    parent = mptt_models.TreeForeignKey('self', null=True, blank=True,
                                        related_name='children', db_index=True)

    class MPTTMeta:
        order_insertion_by = ['name']

我可以用管理界面填充它并显示在网站页面上.

I can fill it with admin interface and show on a site pages.

我可以用django shell填充它:

I can fill it with django shell:

Python 2.7.3 (default, Jun 22 2015, 19:43:34)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from src.catalog.models import Tree
>>> Tree.objects.create(name='1', slug='2')
<Tree: 1>
>>> Tree.objects.all()
[<Tree: 1>]

我编写了一个迁移,该迁移使用旧模型中的信息填充了Tree模型:

I have wrote a migration that fills the Tree model using information from legacy models:

def propagate_tree(app_registry, schema_editor):
    Category = app_registry.get_model('catalog', 'Category')
    Tree = app_registry.get_model('catalog', 'Tree')

    for category in Category.objects.all():
        parent = Tree.objects.create(name=category.title, slug=category.slug)

        for group in category.group_set.all():
            Tree.objects.create(parent=parent, name=group.title, slug=group.slug)

我遇到以下错误:

django.db.utils.IntegrityError: null value in column "lft" violates not-null constraint

在执行该行时:

parent = Tree.objects.create(name=category.title, slug=category.slug)

仍然无法理解此错误的原因:(

Still can not understand the reason of this error :(

推荐答案

我遇到了同样的问题,原因是使用app_registry导入模型. 在迁移中将其替换:

I've just come across the same issue, and the reason is the Model import using the app_registry. Replace this in the migration:

Tree = app_registry.get_model('catalog', 'Tree')

具有常规导入功能,就像在shell中一样.

with the normal import, as you are doing in the shell.

from src.catalog.models import Tree

它应该像魅力一样工作.

And it should work like charm.

但是,我不知道为什么第一个不起作用,因为就我而言,这是在迁移文件中导入模型的首选方式.

However, I don't know why the first one doesn't work, because, as far as I'm concerned, it's the preferred way of importing Models in migration files.

这篇关于django-mptt引发django.db.utils.IntegrityError:列"lft"中的空值.违反非空约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆