title: How to serialize a Django MPTT family and keep it hierarchical?
body: <p>I was trying to find solution for <a href="https://www.questarter.com/q/how-to-serialize-a-mptt-family-and-keep-it-hierarchical-27_45022204.html" rel="nofollow noreferrer">this</a> (<a href="https://webcache.googleusercontent.com/search?q=cache:XA51J_DpR-gJ:https://www.questarter.com/q/how-to-serialize-a-mptt-family-and-keep-it-hierarchical-27_45022204.html%20&amp;cd=1&amp;hl=pt-BR&amp;ct=clnk&amp;gl=br&amp;lr=lang_en%7Clang_pt&amp;client=ubuntu" rel="nofollow noreferrer">Google cache</a>)</p>
  
  <p>
  And I could only came up with a solution like this:</p>
  
  <pre><code>import json
  
  from mptt.utils import tree_item_iterator
  from rest_framework import generics
  from rest_framework.response import Response
  
  from .models import Category
  
  def tree_family_items_to_json(instances):
      data = ''
      channel = '"{}"'.format(instances[0].channel.slug)
      for category, structure in tree_item_iterator(instances):
          if structure['new_level']:
          data += '{'
          else:
              data += '],'
              data += '"channel": {}'.format(channel)
              data += '},{'
          data += '"slug": "{}",'.format(category.slug)
          data += '"name": "{}",'.format(category.name)
          data += '"subcategories": ['
          for level in structure['closed_levels']:
              data += '],'
              data += '"channel": {}'.format(channel)
              data += '}'
  
      return json.loads(data)
  
  class CategoryFamily(generics.RetrieveAPIView):
      lookup_field = 'slug'
      queryset = Category.objects.all()
  
      def retrieve(self, request, *args, **kwargs):
          instances = self.get_object().get_family()
          json_data = tree_family_items_to_json(instances)
          return Response(json_data)
  </code></pre>
  
  
  
  <p>The point is that I used <a href="http://django-mptt.readthedocs.io/en/latest/mptt.utils.html" rel="nofollow noreferrer">tree_item_iterator</a> from mptt and now I'm looking for something more fancy.</p>
  
  <p>It suited the need for a while. But now sure for how long.</p>
  
  
  
  <p>Any ideas?</p>