I have a model:
JavaScript
x
5
1
menuName = models.CharField(max_length=50)
2
menuAlias = models.CharField(max_length=50, unique=True, validators=[aliasvalidator])
3
published = models.BooleanField()
4
parentId = models.IntegerField()
5
And want to build a template which contains menu with limitless parent-child relations for each entry, where parent id’s of the “first-level” elements is 0. And as a result to build any html menu trees I want.
Advertisement
Answer
Don’t re-invent the wheel; use a dedicated Django extension for building tree-structures. There are several packages available that implement a Modified Preorder Tree Traversal model.
Chief among them is django-mptt; it’ll make your menu building much easier and performant:
JavaScript
1
9
1
from django.db import models
2
from mptt.models import MPTTModel, TreeForeignKey
3
4
class Menu(MPTTModel):
5
menuName = models.CharField(max_length=50)
6
menuAlias = models.CharField(max_length=50, unique=True, validators=[aliasvalidator])
7
published = models.BooleanField()
8
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
9