How to build django-mptt tree without recovery after each insert?

I am building a large mptt tree. I would like to insert all the nodes and after that start the method to restore the whole tree:

for i in range(big_loop): ... m.save() # Saving mptt object. Tree is rebuild. some_mptt_model.tree.rebuild() 

How can I avoid restoring a tree after each insertion?

I found only the dropped keyword in the .save method:

In earlier versions, MPTTModel.save () had a raw keyword argument. If True, the MPTT fields will not be updated during the save. This (undocumented) argument is now deleted.

+4
source share
2 answers

You can disable tree recovery after each insertion using the disable_mptt_updates method:

 with MyModel.objects.disable_mptt_updates(): # some bulk updates... for obj in objects: obj.save() # And then you can rebuild the tree. MyModel.objects.rebuild() 
+3
source

Perhaps this can be solved using the Proxy model . In the proxy model, the save method can be overridden to call the save models.Model method instead of the MPTT save method. Something like that:

 class MyNonMPTTModel(MyMPTTModel): class Meta: proxy = True def save(self, *args, **kwargs): super(models.Model, self).save(*args, **kwargs) 

I have not tried this code, but I think it can work.

0
source

Source: https://habr.com/ru/post/1369269/


All Articles