Serializers – Django REST Framework
Last Updated :
06 Nov, 2023
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 advanced serializer fields and arguments. It assumes one is familiar with How to start a project with Django REST Framework.
Creating and Using Serializers
Serializers are used to convert complex data types, such as Django model instances, into Python data types that can 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. Serializers in Django are a part of the Django REST framework, a powerful and flexible toolkit for building Web APIs.
Creating a basic Serializer
To create a basic serializer one needs to import the serializers class from rest_framework and define fields for a serializer just like creating a form or model in Django.
Example
Python3
from rest_framework import serializers
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length = 200 )
created = serializers.DateTimeField()
|
This way one can declare serializer for any particular entity or object based on fields required. Serializers can be used to serialize as well as deserialize the data.
Using Serializer to serialize data
One can now use CommentSerializer to serialize a comment, or list of comments. Again, using the Serializer class looks a lot like using a Form class. Let’s create a Comment class first to create a object of type comment that can be understood by our serializer.
Python3
from datetime import datetime
class Comment( object ):
def __init__( self , email, content, created = None ):
self .email = email
self .content = content
self .created = created or datetime.now()
|
Now that our object is ready, let’s try serializing this comment object. Run following command,
Python manage.py shell
Now run the following code
# import comment serializer
>>> from apis.serializers import CommentSerializer
# import datetime for date and time
>>> from datetime import datetime
# create a object
>>> class Comment(object):
... def __init__(self, email, content, created=None):
... self.email = email
... self.content = content
... self.created = created or datetime.now()
...
# create a comment object
>>> comment = Comment(email='[email protected]', content='foo bar')
# serialize the data
>>> serializer = CommentSerializer(comment)
# print serialized data
>>> serializer.data
Now let’s check output for this,

To check more on how to create and use a serializer visit – Creating and Using Serializers
ModelSerializer
A ModelSerializer typically refers to a component of the Django REST framework (DRF).The Django REST framework is a popular toolkit for building Web APIs in Django applications. It provides a set of tools and libraries to simplify the process of building APIs, including serializers.
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().
Syntax :
Python3
class SerializerName(serializers.ModelSerializer):
class Meta:
model = ModelName
fields = List of Fields
|
Models.py
Python3
from django.db import models
class Account(models.Model):
user_id = model.IntegerField()
account_name = model.CharField(max_lenght = 50 )
user = model.CharField(max_length = 100 )
created = models.DateTimeField(auto_now_add = True )
|
Just like when building a form or model in Django, the first step in establishing a basic serializer is to import the serializers class from the rest framework and define the serializer’s fields.
Example :
Python3
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = [ 'user_id' , 'account_name' , 'user' , 'created' ]
|
By default, all the model fields on the class will be mapped to a corresponding serializer fields.
To checkout how to use ModelSerializer in your project, visit – ModelSerializer in serializers – Django REST Framework.
HyperlinkedModelSerializer
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field. The url field will be represented using a HyperlinkedIdentityField serializer field, and any relationships on the model will be represented using a HyperlinkedRelatedField serializer field.
Syntax :
Python3
class SerializerName(serializers.HyperlinkedModelSerializer):
class Meta:
model = ModelName
fields = List of Fields
|
Example :
Python3
class AccountSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Account
fields = [ 'id' , 'account_name' , 'users' , 'created' ]
|
To checkout how to use HyperLinkedModelSerializer in your project, visit – HyperlinkedModelSerializer in serializers – Django REST Framework.
Serializer Fields
BooleanField |
A boolean field used to wrap True or False values. |
NullBooleanField |
A boolean field that accepts True, False and Null values. |
CharField |
CharField is used to store text representation. |
EmailField |
EmailField is also a text representation and it validates the text to be a valid e-mail address. |
RegexField |
As the name defines, RegexField matches the string to a particular regex, else raises an error. |
URLField |
URLField is basically a RegexField that validates the input against a URL matching pattern. |
SlugField |
SlugField is a RegexField that validates the input against the pattern [a-zA-Z0-9_-]+. |
IPAddressField |
IPAddressField is a field that ensures the input is a valid IPv4 or IPv6 string. |
IntegerField |
IntegerField is basically a integer field that validates the input against Python’s int instance. |
FloatField |
FloatField is basically a float field that validates the input against Python’s float instance. |
DecimalField |
DecimalField is basically a decimal field that validates the input against Python’s decimal instance. |
DateTimeField |
DateTimeField is a serializer field used for date and time representation. |
DateField |
DateField is a serializer field used for date representation. |
TimeField |
Timefield is a serializer field used for time representation. |
DurationField |
DurationField is a serializer field used for duration representation. |
ChoiceField |
ChoiceField is basically a CharField that validates the input against a value out of a limited set of choices. |
MultipleChoiceField |
MultipleChoiceField is basically a CharField that validates the input against a set of zero, one or many values, chosen from a limited set of choices. |
FileField |
FileField is basically a file representation. It performs Django’s standard FileField validation. |
ImageField |
ImageField is an image representation.It validates the uploaded file content as matching a known image format. |
ListField |
ListField is basically a list field that validates the input against a list of objects. |
JSONField |
JSONField is basically a field class that validates that the incoming data structure consists of valid JSON primitives. |
HiddenField |
HiddenField is a field class that does not take a value based on user input, but instead takes its value from a default value or callable. |
DictField |
DictField is basically a dictionary field that validates the input against a dictionary of objects. |
Core arguments in serializer fields
Serializer fields in Django are same as Django Form fields and Django model fields and thus require certain arguments to manipulate the behaviour of those Fields.
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
Serializer Fields - Django REST Framework
Serializer comes with some fields (entries) that process data in and out of the serializer in Django REST Framework. The very motive of Serializing is to convert DB data to a datatype that can be used by javascript. For example, if you have a class with name Employee and its fields as Employee_id, E
13 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
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
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
DictField 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
URL 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
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
String 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
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