How to serialize a API response (in JSON) and modify and add fields to it in Django Rest Framework?

Viewed 2052

I am getting data from different APIs in DRF. However, to enforce modularity I need to serialize the JSON response and make a 'fake' model for each API endpoint I am calling.

I have already created a model and a serializer for an endpoint, but I need to make another API call while serializing previous response I need to modify some of the fields.

from rest_framework import serializers
from django.db import models
from ..nlp_utils.google_nlp import GoogleNLP


class Search(models.Model):
   title = models.CharField(blank=True, default='')
   link = models.CharField(blank=True, default='')
   snippet = models.CharField(blank=True, default='')
   description = models.CharField(blank=True, default='')
   sentiment_score = models.FloatField(blank=True, default=0.0)
   sentiment_magnitude = models.FloatField(blank=True, default=0.0)


class SearchResultSerializer(serializers.ModelSerializer):
    class Meta:
        model = Search
        fields = ('title', 'link', 'snippet', 'description','sentiment_score', 'sentiment_magnitude')`

here I need to call some more endpoints and populate sentiment_score and sentiment_magnitude

2 Answers

You have two options:

Option 1

You can override to_representation method of serializer. Each serializer has a method called to_representation that will create json response that will be passed to users. for example:

class SearchResultSerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        r = super(TodoSerializer, self).to_representation(instance)
        r.update({
        'sentiment_score': 'anything you want here'
        })
        return r

Option 2

Use django rest MethodSerializer fields in your serializer.

class SearchResultSerializer(serializers.ModelSerializer):
    sentiment_magnitude = serializers.SerializerMethodField()

   class Meta:
      model = Search
      fields = '__all__'

   def get_sentiment_magnitude(self, obj):
        sentiment_magnitude = "anything you want here"
        return sentiment_magnitude

Rather than defining it in the model, you can directly attach these fields in the serializer like this(using SerializerMethodField):

class SearchResultSerializer(serializers.ModelSerializer):
        sentiment_score = serializers.SerializerMethodField()
        sentiment_magnitude = serializers.SerializerMethodField()

       class Meta:
          model = Search
          fields = ('title', 'link', 'snippet', 'description','sentiment_score', 'sentiment_magnitude')

       def get_sentiment_magnitude(self, obj):
            # call external api with search obj which has been stored in your previous call
            return data

       def get_sentiment_score(self, obj):
            # call external api with search obj which has been stored in your previous call
            return data

Update

You can use context from any Generic Views or Viewset to pre-populate data. You can try like this:

class YourViewSet(ViewSet):
     ...
     def get_serializer_context(self):
         context = super(YourViewSet, self).get_serializer_context()
         data = get_it_from_api()
         context['sentiment_score'] = data.get('sentiment_score')
         context['sentiment_magnitude'] = data.get('sentiment_magnitude')
         return context

And use it in serializer like this:

class SearchResultSerializer(serializers.ModelSerializer):
        sentiment_score = serializers.SerializerMethodField()
        sentiment_magnitude = serializers.SerializerMethodField()

       class Meta:
          model = Search
          fields = ('title', 'link', 'snippet', 'description','sentiment_score', 'sentiment_magnitude')

       def get_sentiment_magnitude(self, obj):
            return self.context.get('sentiment_magnitude')

       def get_sentiment_score(self, obj):
            return self.context.get('sentiment_score')

Also, even without using the generic views/viewset, you can still pass extra context like this SearchResultSerializer(instance, context={'sentiment_magnitude': sentiment_magnitude, "sentiment_score": sentiment_score}). Please see the documentation.

Related