Skip to content
Advertisement

Building ‘limitless’ menu trees with Django

I have a model:

 menuName = models.CharField(max_length=50)
 menuAlias = models.CharField(max_length=50, unique=True, validators=[aliasvalidator])
 published = models.BooleanField()
 parentId = models.IntegerField()

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:

from django.db import models
from mptt.models import MPTTModel, TreeForeignKey

class Menu(MPTTModel):
    menuName = models.CharField(max_length=50)
    menuAlias = models.CharField(max_length=50, unique=True, validators=[aliasvalidator])
    published = models.BooleanField()
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
Advertisement