Skip to content
thesarfo

Note

Custom Serializer Fields

Adding a computed field to a serializer that isn't present on the underlying model, using SerializerMethodField.

views 0

We all know that our serializers display what is already in our model, that we want our users to see. Now what if we want to display something in the browser that is not in our model. We can do that. see below

from rest_framework import serializers
from decimal import Decimal
from store.models import Product
class ProductSerializer(serializers.Serializer):
id = serializers.IntegerField()
title = serializers.CharField(max_length=255)
unit_price = serializers.DecimalField(max_digits=6, decimal_places=2)
price_with_tax = serializers.SerializerMethodField(method_name='calculate_tax') #new field not in model
def calculate_tax(self, product: Product):
'''this method calculates the tax, we give it the args self, and the product being serialized. later this method is referenced in the serializer field that is going to need the calculation we are performing below'''
return product.unit_price * Decimal(1.1)
# we imported the Decimal class to help us multiply the unit price with 1.1(which is a float)

Now when you save and refresh, it will display the price with tax in our browser, even though that field is not in our model