ModelSerializer in serializers – Django REST Framework

20 Jul, 2020
ModelSerializer is a layer of abstraction over the default serializer that allows to quickly create a serializer for a model in Django. Django REST Framework is a wrapper over default Django Framework, basically used to create APIs of various kinds. There are three stages before creating a API through REST framework, Converting a Model’s data to JSON/XML format (Serialization), Rendering this data to the view, Creating a URL for mapping to the viewset. This article revolves around ModelSerializer in serializers of Django REST Framework.
The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields.The ModelSerializer class is the same as a regular Serializer class, except that:
It will automatically generate a set of fields for you, based on the model.
It will automatically generate validators for the serializer, such as unique_together validators.
It includes simple default implementations of .create() and .update().
class SerializerName(serializers.ModelSerializer):    class Meta:        model = ModelName        fields = List of Fields
Example –
class AccountSerializer(serializers.ModelSerializer):    class Meta:        model = Account        fields = ['id', 'account_name', 'users', 'created']
By default, all the model fields on the class will be mapped to a corresponding serializer fields.
Add rest_framework to INSTALLED_APPS
Create a app and model
Serialization
Creating a viewset
Define URLs of API
Run server and check API
To initialize REST Framework in your project, go to settings.py, and in INSTALLED_APPS add ‘rest_framework’ at the bottom.
# Application definition  INSTALLED_APPS = [    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',    'rest_framework',]
Now, let’s create a app using command,
python manage.py startapp apis
A folder with name apis would have been registered by now. let’s add this app to INSTALLED_APPS and urls.py also.In, settings.py,
# Application definition  INSTALLED_APPS = [    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',    'rest_framework',    'apis',]
Now, add apis urls in urls.py. In geeksforgeeks.urls.py,
from django.contrib import admin# include necessary librariesfrom django.urls import path, include  urlpatterns = [    path('admin/', admin.site.urls),    # add apis urls    path('', include("apis.urls"))]
Create a modelTo demonstrate, creating and using an API, let’s create a model named “GeeksModel”. In apis/models.py
from django.db import models  class GeeksModel(models.Model):    title = models.CharField(max_length = 200)    description = models.TextField()      def __str__(self):        return self.title
now our app is ready, let’s serialize the data and create views from the same.
Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. Let’s start creating a serializer, in file apis/serializers.py,
# import serializer from rest_frameworkfrom rest_framework import serializers  # import model from models.pyfrom .models import GeeksModel  # Create a model serializer class GeeksSerializer(serializers.ModelSerializer):    # specify model and fields    class Meta:        model = GeeksModel        fields = ('title', 'description')
To render data into frontend, and handle requests from user, we need to create a view. In Django REST Framework, we call these as viewsets, so let’s create a view in apis/views.py,
# import viewsetsfrom rest_framework import viewsets  # import local datafrom .serializers import GeeksSerializerfrom .models import GeeksModel  # create a viewsetclass GeeksViewSet(viewsets.ModelViewSet):    # define queryset    queryset = GeeksModel.objects.all()          # specify serializer to be used    serializer_class = GeeksSerializer
Specify the url path of APIs to be accessed, In apis/urls.py,
# basic URL Configurationsfrom django.urls import include, path# import routersfrom rest_framework import routers  # import everything from viewsfrom .views import *  # define the routerrouter = routers.DefaultRouter()  # define the router path and viewset to be usedrouter.register(r'geeks', GeeksViewSet)  # specify URL Path for rest_frameworkurlpatterns = [    path('', include(router.urls)),    path('api-auth/', include('rest_framework.urls'))]
After everything is successfully ready, let’s run some commands to activate the server.
Run following commands to create the database, and run server,
python manage.py makemigrations
python manage.py migrate
python manage.py runserver

Now visit http://127.0.0.1:8000/geeks/,
One can check that ModelSerializer has created a endpoint with overall CRUD functionality.
To check the code for the project, click here
Specifying which fields to includeIf you only want a subset of the default fields to be used in a model serializer, you can do so using fields or exclude options, just as you would with a ModelForm.For example:
class AccountSerializer(serializers.ModelSerializer):    class Meta:        model = Account        # specify field names        fields = ['id', 'account_name', 'users', 'created']
or exclude Example :
class AccountSerializer(serializers.ModelSerializer):    class Meta:        model = Account        # specify field names        exclude = ['id']
Specifying fields explicitlyOne can add extra fields to a ModelSerializer or override the default fields by declaring fields on the class, just as you would for a Serializer class.For example,
class AccountSerializer(serializers.ModelSerializer):    # defining fields manually    url = serializers.CharField(source ='get_absolute_url', read_only = True)      class Meta:        # specify model        model = Account
Specifying read only fieldsOne may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the read_only=True attribute, you can use the shortcut Meta option, read_only_fields.This option should be a list or tuple of field names, and is declared as follows:
class AccountSerializer(serializers.ModelSerializer):    class Meta:        model = Account        fields = ['id', 'account_name', 'users', 'created']        # specify read only fields        read_only_fields = ['account_name']
To check more about ModelSerializer, visit ModelSerializer Documentation
nidhi_biet
Django-REST
Python Django
rest-framework
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts