Last Updated: February 25, 2016
·
1.011K
· exallium

Migrating to django-mptt and Python's MRO

Python's MRO can bite you when you introduce the MPTTModel base class to whatever you're migrating, so make sure that no base class to the left of MPTTModel inherits django's own Model. E.g.

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

class MyMixin(models.Model):
    field1 = models.IntegerField()

# Before the change
class MyModel(MyMixin, models.Model):
    field2 = models.IntegerField()

# After the change
class MyModel(MPTTModel, MyMixin):
    field2 = models.IntegerField()

Not doing this (i.e. having MyMixin to the left of MPTTModel) will cause immediate breakage. This does make sense once you realize what's going on, but it took me quite a while to find the bug, and I figured I'd try to save other people some time.

UPDATE: Note for Migrations, there is a caveat you should look out for when saving new parent data mentioned here: