Entry detail

Django MPTT

Django MPTT is an application I've split out from a project I'm working on - it consists of some utilities for implementing Modified Preorder Tree Traversal (MPTT) with your own Django Model classes and helpers for working with trees of Model instances.

I have a few projects where I've used MPTT to be able to efficiently display trees of Model instances - this application takes some of the logic I'd previously copied and pasted directly into model classes and makes it easy to apply it to any model class.

Example of simplest possible usage:

from django.db import models

from mptt.models import treeify

class Genre(models.Model):
    name = models.CharField(max_length=50, unique=True)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children')

    def __unicode__(self):
        return self.name

treeify(Genre)

Hey, looks like it works:

>>> action = Genre.objects.create(name='Action')
>>> platformer = Genre.objects.create(name='Platformer', parent=action)
>>> platformer_2d = Genre.objects.create(name='2D Platformer', parent=platformer)
>>> platformer_3d = Genre.objects.create(name='3D Platformer', parent=platformer)
>>> from mptt.debug import print_tree
>>> from django.db import connection
>>> initial_query_count = len(connection.queries)
>>> print_tree(Genre.tree.all())
Action
  Platformer
    2D Platformer
    3D Platformer
>>> print len(connection.queries) - initial_query_count
1

Read the application's documentation for information on what's available and implementation details.

Posted by jonny on December 29, 2007

Comments

apollo13 December 29, 2007 at 2:21 p.m.

One word: cool :)

P.S.: Thx for this app

Comments are currently disabled