6

I'm looking for a good way to store and use hierarchical (parent/child) data in Django. I've been using django-mptt, but it seems entirely incompatible with my brain - I end up with non-obvious bugs in non-obvious places, mostly when moving things around in the tree: I end up with inconsistent state, where a node and its parent will disagree on their relationship.

My needs are simple:

  • Given a node:
    • find its root
    • find its ancestors
    • find its descendants
  • With a tree:
    • easily move nodes (ie. change parent)

My trees will be smallish (at most 10k nodes over 20 levels, generally much much smaller, say 10 nodes with 1 or 2 levels).

I have to think there has to be an easier way to do trees in python/django. Are there other approaches that do a better job of maintaining consistency?

Parand
  • 102,950
  • 48
  • 151
  • 186
  • 2
    django-mptt is great - just read some of Daniel Roseman's answer here (http://stackoverflow.com/questions/2324727/re-ordering-child-nodes-in-django-mptt/2326625#2326625) for some help with moving nodes around. Don't give up! – Dominic Rodger Apr 23 '10 at 15:56
  • Thanks, that looks like the likely cause of my issues as well, but I don't trust myself to get that right every time - seems too easy to miss. I'll echo your comment: "Still a bit nervous about MPTT and the possibility of the tree getting into a bad state" :-) I take it you ended up happy? – Parand Apr 23 '10 at 16:00

1 Answers1

4

django-treebeard is another option. It has great documentation. I believe it meets all of your above requirements and includes some functions for checking the tree for problems and fixing those problems in the tree.

Node.find_problems() https://tabo.pe/projects/django-treebeard/docs/1.60/api.html#treebeard.models.Node.find_problems

Node.fix_tree() https://tabo.pe/projects/django-treebeard/docs/1.60/api.html#treebeard.models.Node.fix_tree

Mark Lavin
  • 24,664
  • 5
  • 76
  • 70
  • 1
    For what it's worth I ended up sticking with mptt and working through the issues, although I'm not particularly happy about it. treebeard looks like a good alternative so I'm accepting the answer. – Parand Apr 27 '10 at 23:20