Naive Django mptt branch copier
1 min readOct 25, 2019
Surprisingly, it has not implemented in the project and end up to be customized one
I have a very simple graph here
class Question(MPTTModel):
...
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
My implementation is
def copy_question_node(instance: Question, plan: int = None, parent: Question = None) -> Question:
"""
Copy the attribute of the `question` and return new instance without `parent`
:param instance:
:return:
"""
kwargs = {}
for attr in settings.ATTR_LIST:
kwargs['plan'] = plan
kwargs['parent'] = parent
kwargs[attr] = getattr(instance, attr)
return Question.objects.create(**kwargs)
def copy_children(target_branch: Question, parent: Question = None, new_node: bool = False) -> None:
"""
:param target_branch: The original
:return:
"""
if new_node:
new_node = copy_question_node(target_branch, parent=parent)
else:
new_node = parent
for child in target_branch.children.all():
# Make children of `plan` node
new_child = copy_question_node(child, parent=new_node)
copy_children(child, parent=new_child, new_node=False)
Method call example
def test_copy_branch(self):
plan14 = Question.objects.get(id=82)
copy_children(plan14, new_node=True)
You will get plan14
a new root
node. Feel free to send me Email to correct my code if I am wrong or ping me if the django-mptt
has an updated on it