Skip to content

Instantly share code, notes, and snippets.

@AndrewIngram
Last active December 19, 2015 21:19
Show Gist options
  • Save AndrewIngram/6019684 to your computer and use it in GitHub Desktop.
Save AndrewIngram/6019684 to your computer and use it in GitHub Desktop.
Migrate from old style tree with parent id to django-mptt or Treebeard's nested sets
from itertools import count
def migrate_children(tree_id, node, counter):
for index, child in enumerate(Region.objects.filter(parent=node).order_by('name')):
child.tree_id = tree_id
child.lft = counter.next()
migrate_children(tree_id, child, counter)
child.rgt = counter.next()
child.save()
for index, node in enumerate(Region.objects.filter(depth=1).order_by('name')):
counter = count(1)
node.tree_id = index
node.lft = counter.next()
migrate_children(index, node, counter)
node.rgt = counter.next()
node.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment