django-mptt raises django.db.utils.IntegrityError: null value in column “lft” violates not-null constraint

蹲街弑〆低调 提交于 2020-02-04 01:19:08

问题


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

There is a model:

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.

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>]

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)

I have got the following error:

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

while execute the line:

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

Still can not understand the reason of this error :(


回答1:


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

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.



来源:https://stackoverflow.com/questions/34534183/django-mptt-raises-django-db-utils-integrityerror-null-value-in-column-lft-vi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!