Serializers - Django REST Framework - GeeksforGeeks

10 Sep, 2021
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
ModelSerializer
HyperLinkedModelSerializer
Serializer Fields
Core arguments in serializer fields
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. 
Example  
Python3
# import serializer from rest_frameworkfrom rest_framework import serializers # create a serializerclass 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.
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
# import datetime objectfrom datetime import datetime # create a classclass Comment(object):    def __init__(self, email, content, created = None):        self.email = email        self.content = content        self.created = created or datetime.now()# create a objectcomment = Comment(email ='leila@example.com', content ='foo bar')
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='leila@example.com', 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
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
Example – 
Python3
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 –  
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 in Django are same as Django Form fields and Django model fields and thus require certain arguments to manipulate the behaviour of those Fields. 
saurabh1990aror
simmytarika5
Django-REST
Python Django
rest-framework
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Selecting rows in pandas DataFrame based on conditions