daveslab
daveslab

Reputation: 10310

Django Rest Framework: How to include linked resources in serializer response?

If write my own implementation of a ViewSet, and I want to return some objects, it's pretty simple:

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

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

class MyModel(Model):
  author = ForeignKey(MyOtherModel)
  ...

Is there a way to do something like this?

...
return Response( MyModelSerializer(objects, many=True, include='author').data )

Upvotes: 0

Views: 386

Answers (2)

Soviut
Soviut

Reputation: 91605

What you're looking for is nested relations. This is built into Django REST Framework. By explicitly defining your relation fields in your serializer you can specify many=True which will expand the related object.

From this example http://www.django-rest-framework.org/api-guide/relations/#example

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')

This can return:

{
    '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},
        ...
    ],
}

Upvotes: 1

agconti
agconti

Reputation: 18123

You can use the depth meta attribute on your serializer.

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

Specifying fields explicitly to control how they are serialized.

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

    class Meta:
        model = Account 

Upvotes: 1

Related Questions