By default, all the model fields on the class will be mapped to a corresponding serializer fields.
INSTALLED_APPS = [
'django.contrib.admin' ,
'django.contrib.auth' ,
'django.contrib.contenttypes' ,
'django.contrib.sessions' ,
'django.contrib.messages' ,
'django.contrib.staticfiles' ,
'rest_framework' ,
]
|
Create a app and model
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
,
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
from django.urls import path, include
urlpatterns = [
path( 'admin/' , admin.site.urls),
path('', include( "apis.urls" ))
]
|
Create a model
To 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.
Serialization
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
,
from rest_framework import serializers
from .models import GeeksModel
class GeeksSerializer(serializers.ModelSerializer):
class Meta:
model = GeeksModel
fields = ( 'title' , 'description' )
|
Creating a viewset
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
,
from rest_framework import viewsets
from .serializers import GeeksSerializer
from .models import GeeksModel
class GeeksViewSet(viewsets.ModelViewSet):
queryset = GeeksModel.objects. all ()
serializer_class = GeeksSerializer
|
Define URLs of API
Specify the url path of APIs to be accessed, In apis/urls.py
,
from django.urls import include, path
from rest_framework import routers
from .views import *
router = routers.DefaultRouter()
router.register(r 'geeks' , GeeksViewSet)
urlpatterns = [
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 server and check API
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
Advanced Usage
Specifying which fields to include
If 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
fields = [ 'id' , 'account_name' , 'users' , 'created' ]
|
or exclude Example :
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
exclude = [ 'id' ]
|
Specifying fields explicitly
One 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):
url = serializers.CharField(source = 'get_absolute_url' , read_only = True )
class Meta:
model = Account
|
Specifying read only fields
One 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' ]
read_only_fields = [ 'account_name' ]
|
To check more about ModelSerializer, visit ModelSerializer Documentation
Core arguments in serializer fields
Argument |
Description |
read_only |
Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization |
write_only |
Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation. |
required |
Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance. |
default |
If set, this gives the default value that will be used for the field if no input value is supplied. |
allow_null |
Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value. |
source |
The name of the attribute that will be used to populate the field. |
validators |
A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. |
error_messages |
A dictionary of error codes to error messages. |
label |
A short text string that may be used as the name of the field in HTML form fields or other descriptive elements. |
help_text |
A text string that may be used as a description of the field in HTML form fields or other descriptive elements. |
initial |
A value that should be used for pre-populating the value of HTML form fields. |
Similar Reads
HyperlinkedModelSerializer in serializers - Django REST Framework
HyperlinkedModelSerializer 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
7 min read
ListField in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_n
4 min read
IPAddressField in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_n
4 min read
JSONField in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_n
4 min read
HiddenField in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_n
4 min read
Nestest Serializer in Django Framework
In web development, creating and consuming APIs (Application Programming Interfaces) is commonplace. Django Rest Framework (DRF) serves as a robust toolkit for building APIs in Django-based web applications. Within DRF, a pivotal concept is serializers. In this article, we will delve into the concep
4 min read
Numeric fields in serializers - Django REST Framework
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_n
5 min read
Serializer Relations - Django REST Framework
Serialization is one of the most important concepts in RESTful Webservices. It facilitates the conversion of complex data (such as model instances) to native Python data types that can be rendered using JSON, XML, or other content types. In Django REST Framework, we have different types of serialize
15+ min read
Serializers - Django REST Framework
The serializers in the REST framework work very similarly to Djangoâs Form and ModelForm classes. The two major serializers that are most popularly used are ModelSerializer and HyperLinkedModelSerialzer. This article revolves around how to use serializers from scratch in Django REST Framework to adv
7 min read
Get Request.User in Django-Rest-Framework Serializer
In Django Rest Framework (DRF), serializers are used to transform complex data types, such as queryset and model instances, into native Python data types. One common requirement is to access the request.user within a serializer, which is particularly useful when you need to customize the serializati
5 min read