What's the best way to serialize more than one model to json in Django 1.6?
<p>I have 3 models show as below.</p>

<pre><code>    class DocumentClass(models.Model):
        text = models.CharField(max_length=100)


    class DocumentGroup(models.Model):
        text = models.CharField(max_length=100)
        documentclass = models.ForeignKey(DocumentClass)


    class DocumentType(models.Model):
        text = models.CharField(max_length=100)
        documentgroup = models.ForeignKey(DocumentGroup)
</code></pre>

<p>And my goal is something like this:</p>

<pre><code>[
    {
        'pk': 1,
        'model': 'DocumentClass',
        'fields':{
            'text':'DocumentClass1',
            'documentgroup':
            [
                {
                    'pk': 1,
                    'model': 'DocumentGroup'
                    'field':
                    {
                        'text':'DocumentGroup1'
                    }
                }
            ]
        }
    },
    {
        'pk': 2,
        'model': 'DocumentClass',
        'fields':{
            'text':'DocumentClass2'
        }
    }
]
</code></pre>

<p>I usually serialize a model by </p>

<pre><code>jsonstr = serializers.serialize("json", DocumentType.objects.all())
</code></pre>

<p>But for my goal. I have no idea.
As the title. What is the best way to do that?</p>

<p>Edit:
The relation of above models look like:</p>

<pre><code>DocumentClass1
|-DocumentGroup1
| |-DocumentType1
| |-DocumentType2
| |-...
|-DocumentGroup2
| |-...
DocumentClass2
|-DocumentGroup...
| |-DocumentType...
</code></pre>

<p>Hi @nofinator and other django rookie like me!
Thanks @nofinator for the great answer! And for django rookies like me. If you want to use django-rest-framework to serialize queryset <strong>DO NOT FORGET</strong> to use the ** <strong>related_name</strong> **(without ** ) attribute in the model like this:</p>

<pre><code>class DocumentClasses(models.Model):
    text = models.CharField(max_length=100)


class DocumentGroups(models.Model):
    text = models.CharField(max_length=100)
    documentclass = models.ForeignKey(DocumentClasses, **related_name**='documentgroups')


class DocumentTypes(models.Model):
    text = models.CharField(max_length=100)
    documentgroup = models.ForeignKey(DocumentGroups, **related_name**='documenttypes')
</code></pre>

<p>@nofinator and ralated_name made my day! Million thanks!</p>

python json serialization django-views