I am trying to model a tree structure within django. This is a reduced version of what I’ve got:
from django.db import models
class Node(models.Model):
parent = models.ForeignKey("Node", null=True)
name = models.CharField(max_length=20)
def child_cnt(self):
return self.node_set.count()
def __unicode__(self):
return self.name
So far so good. It works. But if I now start to create a hierarchy like that:
from ....models import Node
root = Node()
root.name = "ROOT"
root.parent = None
root.save()
n = Node()
print n.child_cnt()
>> 1
print n.node_set.all()
[<Node: ROOT>]
So what does the root node make as a child inside n? And how can I avoid that?
The problem disappears once I called n.save() but it is kind of nasty to see a node initialized with a child_cnt of 1 inside the admin site.
I know that sounds crazy, but I spent a few minutes trying to solve your problem and It didnt work in any attempt that I tried.
Anyways, for the Tree ForeignKey, I find another solution Online, which is a entire library that takes care of this type of Key, https://github.com/django-mptt/django-mptt
You can try it out, it might fit for you. I hate having to add a library for such a small thing, however I could not find anything better.
Also if you dont wanna import the entire lib, you can kind of bring just the TreeForeignKey to your code.