Reputation: 21
I have a model serializer TestSerializer.
class Test(models.Model):
name = models.CharField(max_length=255)
email = models.EmailField(max_length=255)
class TestSerializer(serializers.ModelSerializer):
class Meta:
model = Test
fields = ('name', 'email')
My question is that I want to add a field called 'profile_url' to the serialized output data. This profile_url field is calculated by making call to another API which returns profile_url based on user_id. Now, the simplest way I can think of is to do this by overriding to_representation method and calling API in that method and return it, but it means that the API call will be made for each record that gets serialized. Is there a way in django-rest-framework, where I'll get the list of serialized objects and I can modify them before outputting it ?
Upvotes: 2
Views: 1050
Reputation: 20976
You should override the view so that you gather all the data you need, inject them back to the test instances and then serialize the whole.
Make sure to explicitly declare the field within the TestSerializer
using the source argument to match the attribute you added in the earlier step.
Upvotes: 1