How to Add a Custom Field in ModelSerializer in Django
Last Updated :
23 Jul, 2025
A key component of Django Rest Framework (DRF) is the Serializer, which converts complex data types like Django models into JSON, XML, or other content types. The ModelSerializer, a subclass of Serializer, automatically creates fields based on the model’s fields, significantly reducing boilerplate code.
Use of Custom Field in ModelSerializer
However, there are situations where the fields in our model may not fully capture the data you need to expose through your API. For instance, we might want to add calculated fields or include data from related models that aren’t present in the current model. In such cases, adding a custom field to your ModelSerializer becomes essential.
Add a Custom Field in ModelSerializer in Django
Before we dive into the specifics of adding a custom field, let’s set up a basic Django project with a simple model to work with.
Step 1: Create a Django Project
First, create a new Django project and app by running the following command in the terminal:
django-admin startproject custom_field_example
cd custom_field_example
python manage.py startapp myapp
Add the new app, myapp, to the INSTALLED_APPS in the settings.py file:
Python
INSTALLED_APPS = [
...
'myapp',
'rest_framework',
]
Django Project StructureStep 3: Create a Simple Model
Now, let’s define a simple model in the models.py file of myapp:
myapp/models.py
Python
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
description = models.TextField()
def __str__(self):
return self.name
After defining the model, run the following commands to create and apply the database migrations:
python manage.py makemigrations
python manage.py migrate
Access the Django Shell
Run the following command in the terminal to open the Django shell:
python manage.py shell
Now, we can create and save instances of the Product model using Django's ORM. Here's how we can add a few sample products:
Python
from myapp.models import Product
# Adding a single product
product1 = Product(name='Laptop', price=1200.00, description='A high-performance laptop')
product1.save()
# Adding another product
product2 = Product(name='Smartphone', price=800.00, description='A smartphone with a great camera')
product2.save()
#You can verify that the data was added correctly by running
# a query to retrieve all the products:
products = Product.objects.all()
for product in products:
print(product.name, product.price, product.description)
exit()
Django ShellStep 4: Create a ModelSerializer
Now that we have a Product model, let’s create a ModelSerializer for it in serializers.py.
This serializer will handle the automatic serialization of the Product model fields (name, price, and description).
myapp/serializers.py
Python
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['name', 'price', 'description']
Add a Custom Field in ModelSerializer
To add a custom field to the ProductSerializer, we need to declare the field manually and define how its value is obtained. Custom fields can be static values, calculated from the model fields, or derived from other sources.
Adding a "discount_price" Custom Field
Let’s say we want to add a discount_price field, which calculates a 10% discount on the product’s price. Here’s how we can do that:
myapp/serializers.py
Python
from rest_framework import serializers
from .models import Product
from decimal import Decimal
class ProductSerializer(serializers.ModelSerializer):
discount_price = serializers.SerializerMethodField()
class Meta:
model = Product
fields = ['name', 'price', 'description', 'discount_price']
def get_discount_price(self, obj):
# 10% discount
return obj.price * Decimal(0.9)
Step 5: Add the View and URL
Now that we have our serializer with a custom field, let’s create a view to expose our serialized data via an API endpoint.
Create a View: myapp/views.py
Python
from rest_framework import generics
from .models import Product
from .serializers import ProductSerializer
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
Finally, register the view in the urls.py file:
Python
from django.contrib import admin
from django.urls import path
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.ProductList.as_view(), name='product-list'),
]
Testing the API
To test the API, run the Django development server:
python manage.py runserver
Now, you can visit http://localhost:8000/ to see the serialized product data, including the custom discount_price field.
OutputAdvantages of Adding Custom Fields in ModelSerializer
- Code Reusability: We can create methods to handle complex logic for custom fields, which can then be reused across different serializers or views.
- Performance: Since custom fields are calculated only when needed, they don’t affect the underlying database structure. This can improve performance when working with complex models.
- Separation of Concerns: By using SerializerMethodField, we keep our business logic (e.g., calculating a discount) within the serializer, separate from the model and views. This results in cleaner and more maintainable code.
Conclusion
In this article, we have covered how to add a custom field to a ModelSerializer in Django. Custom fields provide flexibility to include additional or computed data that may not exist directly in the database. With a clear understanding of how SerializerMethodField works, we can now extend the capabilities of our Django REST APIs to suit our project’s requirements.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice