Open In App

Django REST Framework: Adding Additional Field to ModelSerializer

Last Updated : 06 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Django REST Framework (DRF) is a powerful and flexible toolkit for building Web APIs in Django. One of its key features is the ModelSerializer class, which provides a shortcut for creating serializers that deal with Django model instances and querysets. However, there are times when you may need to add additional fields to a ModelSerializer that are not part of the underlying model. This article will guide you through the process of adding these extra fields.

What is ModelSerializer in Django?

ModelSerializer is a subclass of Django REST Framework's Serializer class. It provides a simple way to create serializers based on Django models, automatically handling the creation of fields, validation, and even saving instances. By using ModelSerializer, you can easily convert model instances to JSON and vice versa, making it a fundamental tool for creating RESTful APIs with Django.

Django REST Framework: Adding Additional Field to ModelSerializer

Step 1: Set Up the Project

First, create a new Django project and application. If you don't have Django and Django REST Framework installed, you can install them using pip:

pip install django djangorestframework

Create a new project and application:

django-admin startproject myproject
cd myproject
django-admin startapp myapp

Add rest_framework and your new application to the INSTALLED_APPS in myproject/settings.py:

INSTALLED_APPS = [
...
'rest_framework',
'myapp',
]
f2

Step 2: Create a Model

In myapp/models.py, define a simple model. For example:

Python
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    published_date = models.DateField()

    def __str__(self):
        return self.title

add model in admin.py file

Python
from django.contrib import admin
from myapp.models import Book
# Register your models here.

admin.site.register(Book)

Run the migrations to create the database table for this model:

python manage.py makemigrations
python manage.py migrate

Createsuperuser using below command and add data in database

python manage.py createsuperuser
d2


Step 3: Create a ModelSerializer

In myapp/serializers.py, create a ModelSerializer for the Book model:

Python
from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'published_date']

Step 4: Add Additional Field to ModelSerializer

Suppose you want to add an additional field, summary, to the BookSerializer. This field is not part of the Book model but is calculated or provided through some other means. Here's how you can add it:

In this example, the summary field is generated using the get_summary method, which concatenates the title, author, and published date.

Python
class BookSerializer(serializers.ModelSerializer):
    summary = serializers.SerializerMethodField()

    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'published_date', 'summary']

    def get_summary(self, obj):
        return f"{obj.title} by {obj.author}, published on {obj.published_date}"

Step 5: Create a ViewSet and URL Configuration

Create a ViewSet in myapp/views.py to handle API requests:

Python
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

Configure the URL routing in myproject/urls.py:

Python
from django.contrib import admin
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from myapp.views import BookViewSet

router = DefaultRouter()
router.register(r'books', BookViewSet)


urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include(router.urls)),
]

Step 6: Testing the API

Run the development server:

python manage.py runserver

You can now access the API at http://127.0.0.1:8000/api/books/. When you retrieve a list of books or a single book, the summary field will be included in the serialized output.

add2

Conclusion

Adding additional fields to a ModelSerializer in Django REST Framework is a straightforward process that involves defining the extra fields in the serializer and providing the logic to populate these fields. This allows you to extend the functionality of your API without modifying the underlying model, making your code more flexible and maintainable. With this knowledge, you can enhance your Django REST APIs to better meet the needs of your applications.


Next Article
Article Tags :
Practice Tags :

Similar Reads