[Django]-Retrieve related field's object in GET requests, otherwise use only ID of the object in POST, PUT, DELETE etc

4👍

It is a common problem, every time when you want to change representation behavior you are free to use to_representation method of a serializer:

class ArticleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Provider
        fields = ('pk', 'title', 'slug', 'body', 'category')

    def to_representation(self, instance):
        representation = super(ArticleSerializer, self).to_representation(instance)
        representation['category'] = CategorySerializer(instance.category).data
        return representation

Leave a comment