4

is there any simple way to serialize a tree given by a model such as the Category shown below?

I'd like to get a json object like:

[ { 'name': 'cat1',
    'children': [ { 'name': 'cat11',
                    'children': [ ... ]
                ]
  }
  ...
]

Thanks

class Category(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
    order_key = models.IntegerField()

    class Meta:
        verbose_name_plural = 'Categories'

    class MPTTMeta:
        order_insertion_by = ['order_key']

    def __unicode__(self):
        return "%s" %(self.name)
jul
  • 36,404
  • 64
  • 191
  • 318

2 Answers2

5

I think you'll have to walk the tree, and build an object which you serialize using JSON. I'm assuming your tree is acyclic, because otherwise it gets more complicated. I haven't tested this, but something like this will work (as long as you're sure you don't have cycles):

def serialize_to_json(self):
    return json.dumps(self.serializable_object())

def serializable_object(self):
    "Recurse into tree to build a serializable object"
    obj = {'name': self.name, 'children': []}
    for child in self.get_children():
        obj['children'].append(child.serializable_object())
    return obj

(Can't remember if children_set is the right way to get the list of children. Please comment if this is wrong.)

Leopd
  • 41,333
  • 31
  • 129
  • 167
0

Maybe Tasypie or Django-Piston can help? If not you can have a look at their source code to get some hints on how to do this.

Pickels
  • 33,902
  • 26
  • 118
  • 178