django-polymorphic / django-polymorphic-tree

Polymorphic MPTT tree support for models
Other
170 stars 45 forks source link

Error: "trying to add a non-nullable field 'level' to component without a default" #81

Open BrendanSimon opened 3 years ago

BrendanSimon commented 3 years ago

I'm trying to modify a project to use django-polymorphic-tree.

The project has 4 models (called A, B, C, D) all derived from a base model (called Component). Each A instance contains a set of B items (via FK), and each of those B items contains a set of C items (via FK), each of those C items contains a set of D items. There is another model called T, which as a FK to Component. Each of A, B, C, D items can have a set of T items.

First, it seems the docs/examples are a little out of date (as I get errors with django 3.1.4).

TypeError: __init__() missing 1 required positional argument: 'on_delete'

I added on_delete=models.SET_NULL to the PolymorphicTreeForeignKey(...) statement in the PolymorphicMPTTModel subclass to solve this. Is this correct?

My project was using django-polymorphic and I have changed the base class (called Component) as follows.

# class Component(PolymorphicModel):
class Component(PolymorphicMPTTModel):

    parent = PolymorphicTreeForeignKey('self', blank=True, null=True, related_name='children', verbose_name='parent', on_delete=models.SET_NULL)

    class Meta(PolymorphicMPTTModel.Meta):
        verbose_name = "Tree node"
        verbose_name_plural = "Tree nodes"

Is that correct?

When I try to makemigrations I get errors about mptt fields (level, lft, ...) not having defaults.

**How do I handle these?***

$ rm db.sqlite3
$ ./manage.py makemigrations
You are trying to add a non-nullable field 'level' to component 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 with a null value for this column)
 2) Quit, and let me add a default in models.py

NOTE: using Django 3.1.4 with Python 3.7.3 on Debian Buster (10.7) operating system.

Thanks for any help - Brendan.