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>You can use the <a href="http://www.django-rest-framework.org/api-guide/serializers/#specifying-nested-serialization" rel="nofollow">depth</a> meta attribute on your serializer.</p>

<pre><code>class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = ('id', 'account_name', 'users', 'created')
        depth = 1
</code></pre>

<p>Specifying fields explicitly to control how they are serialized. </p>

<pre><code>class AccountSerializer(serializers.ModelSerializer):
    url = serializers.CharField(source='get_absolute_url', read_only=True)
    groups = serializers.PrimaryKeyRelatedField(many=True)

    class Meta:
        model = Account 
</code></pre>

python django django-rest-framework