Search code examples
pythondjangotreenodes

Trees with Django models - different approaches


I'm trying to make a simple tree app that accepts a user's input and adds nodes to a tree structure based on the input. I want every node of the tree to be an instance of a general model, called nodes.

An entry has up to two parts: a parent, which is the beginning of the string up to the first parentheses, and a child, which is in parentheses.

For example, let's say a user enters the following:

"animal(cat)"
"animal(dog)"
"dog(golden retriever)"
"organic_life_form(animal)"

This should generate a tree of this structure:

organic_life_form
        |
     animal
   /         \
dog            cat
  |
golden retriever

I made a mistake defining my 'node' model, but I'm not sure how to fix it.

class Node(models.Model):
    name = models.CharField(max_length=200)
    parent = models.ForeignKey(Node)
    nodes = models.IntegerField(default=0)

    def __unicode__(self):
        return self.name 

Apparently I am not allowed to use another node as my foreign key "parent", as "Node" isn't yet defined. This seems like a pretty basic error, but I still don't understand why one isn't allowed to do this.

Can anyone explain why I am unable to use another "Node" as a foreign key? And if it's a lost cause, what might be a better way of defining the type of structure I want?


Solution

  • Node isn't available within the class definition, as it has not yet been defined. To permit this, Django allows you to use the name as a string in quotes.

    However for your underlying problem you should probably look into an existing library like django-mptt.