开发者

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

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 (u开发者_StackOverflow中文版ndocumented) argument has now been removed.


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()


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜