Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add django-mptt rebuild to migration?

I have add the django-mptt to existing database, and create the new migration.

Migration process was asked for default values for level, left, right and such fields, but doesn't add the model.rebuild operation to migration file.

How to add rebuild operation to migration file manually?

like image 453
Y.N Avatar asked Oct 16 '25 04:10

Y.N


1 Answers

Try the following:

from __future__ import unicode_literals
from django.db import migrations
from mptt import register, managers


def rebuild_tree(apps, schema_editor):
    YourMPTTModel = apps.get_model('your_app', 'YourMPTTModel')

    manager = managers.TreeManager()
    manager.model = YourMPTTModel

    register(YourMPTTModel)

    manager.contribute_to_class(YourMPTTModel, 'objects')
    manager.rebuild()


class Migration(migrations.Migration):


  operations = [
      migrations.RunPython(
          rebuild_tree
      )
  ]
like image 183
Iury Alves de Souza Avatar answered Oct 18 '25 17:10

Iury Alves de Souza