Search code examples
pythondjangodjango-mpttmptt

Django mptt database migration error


im trying to get mptt working with my current project, but having issues with the database migration.

here is my model

from django.db import models
from mptt.models import MPTTModel, TreeForeignKey

class Section(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)

    class MPTTMeta:
        order_insertion_by = ['name']

and im running this in the command line:

sudo python manage.py makemigrations core

but seem to be getting and error related to the level field

You are trying to add a non-nullable field 'level' to section without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
Select an option:

what should I do?


Solution

  • 'Level' is automatically added by MPTTModel to denote the 'depth' of a particular node in the tree. If you haven't created the tree structure yet, it should be safe to choose option 1 and default everything to level 0 (root). If you do not have the tree structure set up yet, this should be fine and should get adjusted as you work with the tree later.

    If you already have a tree structure in mind and you need to reflect that in your data, you will still need to do this, but you will need to follow it with a (probably handwritten) data migration to set the right values.