Representing hierarchical data with Django and MPTT

Picture 3

Apparently, you’ve got two options for managing hierarchical data in djangodjango-mptt and django-treebeard. I didn’t have any time to test both of them carefully, so I just played a bit with the first one (and with great results!). [p.s. the comparison table above is not mine, but I found it quite useful. Click on the image to find out how it was created… ]

I guess that the key feature I was looking for is the admin-integration. Trees must be displayed and edited properly in the admin… unfortunately both projects don’t provide that feature by default, but luckily for there are attempts (#1 and #2) to fix this issue.

In order to use MPTT with your models you just have to download it, add it to your ‘installed application’ settings and register the models you intend to use:

# A mimimal example usage of ``mptt.register`` is given below, where the
#  model being set up for MPTT is suitable for use with the default
# arguments which specify fields and the tree manager attribute::

   from django.db import models

   import mptt

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

   mptt.register(Genre, order_insertion_by=['name'])

Then, after installing the patches, create a tree-friendly admin by subclassing MpttModelAdmin (check out the docs for more info).

Picture 4

Here’s the result – not bad at all! I just had to install django-mptt and the patches needed for using the jquery nested-sortable library with the admin. I’ll be working more on this during the next days so probably I’ll be posting more stuff….

 

Share/Bookmark






3 Responses to “Representing hierarchical data with Django and MPTT”

[…] MPTT #2 Posted in programming by magicrebirth on August 18, 2009 This is a follow up to the previous post on managing and visualizing trees using django. I’ve been using MPTT quite a bit now and it’s great – also, I looked deeper into […]

Django admin and MPTT #2 « Parerga und Paralipomena added these pithy words on Aug 18 09 at 10:46 am

hey I posted a follow up to this: http://www.michelepasin.org/blog/?p=275

magicrebirth added these pithy words on Aug 18 09 at 10:47 am

Actually you can easily rebuild/fix existing trees with mptt with my patch from http://code.google.com/p/django-mptt/issues/detail?id=13.

I’m using that technique for years.. :) Some people commented on issue that it rocks too. Not sure why upstream does not want to include this, but.. :)

Vadim Fint added these pithy words on Mar 21 10 at 12:59 am