Django Rest Framework: How to include linked resources in serializer response?
<p>If write my own implementation of a <code>ViewSet</code>, and I want to return some objects, it's pretty simple:</p>

<pre><code>class MyViewSet(ViewSet):
  def my_method(self, request):
    objects = MyModel.objects.all()
    return Response( MyModelSerializer(objects, many=True).data )
</code></pre>

<p>But let's say that I want to include the actual instance of another linked resource by a <code>ForeignKey</code>, <strong>instead of</strong> just an ID. For example:</p>

<pre><code>class MyModel(Model):
  author = ForeignKey(MyOtherModel)
  ...
</code></pre>

<p>Is there a way to do something like this?</p>

<pre><code>...
return Response( MyModelSerializer(objects, many=True, include='author').data )
</code></pre>

<p>What you're looking for is <a href="http://www.django-rest-framework.org/api-guide/relations/" rel="nofollow">nested relations</a>. This is built into Django REST Framework. By explicitly defining your relation fields in your serializer you can specify <code>many=True</code> which will expand the related object. </p>

<p>From this example <a href="http://www.django-rest-framework.org/api-guide/relations/#example" rel="nofollow">http://www.django-rest-framework.org/api-guide/relations/#example</a></p>

<pre><code>class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ('order', 'title', 'duration')

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True, read_only=True)

    class Meta:
        model = Album
        fields = ('album_name', 'artist', 'tracks')
</code></pre>

<p>This can return:</p>

<pre><code>{
    'album_name': 'The Grey Album',
    'artist': 'Danger Mouse',
    'tracks': [
        {'order': 1, 'title': 'Public Service Announcement', 'duration': 245},
        {'order': 2, 'title': 'What More Can I Say', 'duration': 264},
        {'order': 3, 'title': 'Encore', 'duration': 159},
        ...
    ],
}
</code></pre>

python django django-rest-framework