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 :(
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With