I have a Django model which has a ForeignKey to the same class, effectively making a tree:
class Tag(models.Model):
name = models.CharField(max_length=50)
parent = models.ForeignKey('self', blank=True, null=True)
Playing around with a recursive in the Django shell (./manage.py shell
), I am easily able to represent the tree as plain text:
def nodes(parent, level):
children = Tag.objects.filter(parent=parent)
for c in children:
spaces = ""
for i in xrange(0,level):
spaces+=" "
print "%s%s" % (spaces,c.name)
nodes(c.pk,level+1)
nodes(None,0)
What I am unsure of is how to get the entire tree into a Django template. I've created a custom template tag to make this easier, but I can't figure out how to pass the data to the template to easily iterate over the tree for display in a template. Here's the basic template tag.
@register.inclusion_tag("core/tags.html")
def render_tags(**kwargs):
tags = Tag.objects.all()
return {"tags":tags}
I know the above is very basic, I just am not sure where to go from here. I thought it might be easier if the Tag class had a function to get its children, so I also have on the class:
def children(self):
return Tag.objects.filter(parent=self.pk)
I use self.pk
there, then the root of the tree is simply rootTag=Tag()
, since it has no pk since it is not saved, rootTag.children()
will find any Tags which do not have a parent Tag, and any of these tags can then just continue to have their children()
function called. But like I said, I do not know how to turn this into a single data structure of some sort to pass to my template.
Thoughts? I think I probably want to build a kind of dict, I'm just not able to follow through here.