How to Add a Custom Field in ModelSerializer in Django
Last Updated :
02 Oct, 2024
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.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read