V
V
Vladimir Kuts2016-05-11 16:40:05
Django
Vladimir Kuts, 2016-05-11 16:40:05

MPTT tree copying branches?

Maybe someone faced a problem:
There is a PolymorphicMPTTModel tree. A task has appeared - if the parent of an arbitrary branch changes, then we copy the data of the branch to a new place, leaving a copy of the branch with the old id with the "deleted" object marks in the old place.
I intercept the saving of the object, look - if its parent changes - then I create a branch with the topology of the old branch, copying the data using the self.get_descendants(include_self=True) generator. And I change the parent of the original branch to a new one.
Everything is fine - only now a copy of the deleted branch - with new id - that is, the branch has been moved to a new location, and in its place there is a deleted branch with NEW id.
How to leave the OLD id of the deleted branch with the least blood, and create new ones for the moved one?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anatoly Scherbakov, 2016-05-11
@fox_12

As I understand it, the problem you have is that you are intercepting the save when it parenthas already been changed. I would do it like this.

class MyModel(models.Model):
    def __init__(self, *args, **kwargs):
        super(MyModel, self).__init__(*args, **kwargs)
        self._initial_parent = self.parent

    def save(self, *args, **kwargs):
        new_parent = self.parent
        if new_parent != self._initial_parent:
            # Marking old branch as obsolete
            self.descendants().update(is_deleted=True)

            # Now, creating a new branch (with new IDs) at the destination node
            root = MyModel.objects.create(parent=new_parent, ...)
            [MyModel.objects.create(...) ...]

            # And cancelling the moving of the current element
            self.parent = self._initial_parent
            self.is_deleted = True

        return super(MyModel, self).save(*args, **kwargs)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question