Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

Serializers – Django REST Framework

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. The serializers in 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

Creating a basic Serializer

To create a basic serializer one needs to import serializers class from rest_framework and define fields for a serializer just like creating a form or model in Django. 



# import serializer from rest_framework
from rest_framework import serializers
# create a serializer
class CommentSerializer(serializers.Serializer):
    # initialize fields
    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.  


# import datetime object
from datetime import datetime
# create a class
class Comment(object):
    def __init__(self, email, content, created = None): = email
        self.content = content
        self.created = created or
# create a object
comment = Comment(email ='', content ='foo bar')

Now that our object is ready, let’s try serializing this comment object. Run following command, 

Python 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):
... = email
...         self.content = content
...         self.created = created or

# create a comment object
>>> comment = Comment(email='', content='foo bar')

# serialize the data
>>> serializer = CommentSerializer(comment)

# print serialized data

Now let’s check output for this, 


To check more on how to create and use a serializer visit – Creating and Using 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 –  


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. 
To checkout how to use ModelSerializer in your project, visit – ModelSerializer in serializers – Django REST Framework


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 –  


class SerializerName(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = ModelName
        fields = List of Fields

Example – 


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

Field NameDescription
BooleanFieldA boolean field used to wrap True or False values.
NullBooleanFieldA boolean field that accepts True, False and Null values.
CharFieldCharField is used to store text representation.
EmailFieldEmailField is also a text representation and it validates the text to be a valid e-mail address.
RegexFieldAs the name defines, RegexField matches the string to a particular regex, else raises an error.
URLFieldURLField is basically a RegexField that validates the input against a URL matching pattern.
SlugFieldSlugField is a RegexField that validates the input against the pattern [a-zA-Z0-9_-]+.
IPAddressFieldIPAddressField is a field that ensures the input is a valid IPv4 or IPv6 string.
IntegerFieldIntegerField is basically a integer field that validates the input against Python’s int instance.
FloatFieldFloatField is basically a float field that validates the input against Python’s float instance.
DecimalFieldDecimalField is basically a decimal field that validates the input against Python’s decimal instance.
DateTimeFieldDateTimeField is a serializer field used for date and time representation.
DateFieldDateField is a serializer field used for date representation.
TimeFieldTimefield is a serializer field used for time representation.
DurationFieldDurationField is a serializer field used for duration representation.
ChoiceFieldChoiceField is basically a CharField that validates the input against a value out of a limited set of choices.
MultipleChoiceFieldMultipleChoiceField is basically a CharField that validates the input against a set of zero, one or many values, chosen from a limited set of choices.
FileFieldFileField is basically a file representation. It performs Django’s standard FileField validation.
ImageFieldImageField is an image representation.It validates the uploaded file content as matching a known image format.
ListFieldListField is basically a list field that validates the input against a list of objects.
JSONFieldJSONField is basically a field class that validates that the incoming data structure consists of valid JSON primitives.
HiddenFieldHiddenField 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.
DictFieldDictField 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_onlySet 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_onlySet 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.
requiredSetting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance.
defaultIf set, this gives the default value that will be used for the field if no input value is supplied.
allow_nullNormally 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.
sourceThe name of the attribute that will be used to populate the field.
validatorsA list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return.
error_messagesA dictionary of error codes to error messages.
labelA short text string that may be used as the name of the field in HTML form fields or other descriptive elements.
help_textA text string that may be used as a description of the field in HTML form fields or other descriptive elements.
initialA value that should be used for pre-populating the value of HTML form fields.

My Personal Notes arrow_drop_up
Last Updated : 10 Sep, 2021
Like Article
Save Article
Similar Reads
Related Tutorials