4

I'm building large mptt tree. I'd like to insert all nodes and after that start method for rebuilding 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 rebuilding tree after each insert?

I've found only depracted keyword in .save method:

In earlier versions, MPTTModel.save() had a raw keyword argument. If True, the MPTT fields would not be updated during the save. This (undocumented) argument has now been removed.

Spodym
  • 173
  • 1
  • 9
  • I don't think so, at least as far as MPTT goes you should rebuild part of the tree index on the right side of inserted item after every insert. With MPTT reads are very cheap while updates are very expensive. Although rather then looping over right hand items you could just update their index +2 in one go. – Davor Lucic Sep 08 '11 at 10:21

2 Answers2

4

You can disable rebuilding tree after each insert using 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()
laszchamachla
  • 763
  • 9
  • 21
0

Maybe this can be solved with a help of Proxy models. In proxy model, save method could be overriden to call savemethod of models.Model instead of MPTT save method. Something like this:

class MyNonMPTTModel(MyMPTTModel):
    class Meta:
        proxy = True

    def save(self, *args, **kwargs):
        super(models.Model, self).save(*args, **kwargs)

I did not try this code, but I guess it could work.

bmihelac
  • 6,233
  • 34
  • 45