Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 295
souvik das Avatar asked Oct 23 '25 03:10

souvik das


1 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
like image 159
Reza Torkaman Ahmadi Avatar answered Oct 25 '25 17:10

Reza Torkaman Ahmadi