DRF Serializer in Python
What is DRF?
DRF stands for Django RST Framework which is a flexible and powerful toolkit that helps you in building APIs for websites.
What is an API?
An API (Application Programming Interface) is a set of rules and definitions which is used to build and integrate an application software. It helps two or more programs communicate with each other and perform certain operations.
What are Serializers?
Serializing is a process of storing an object state or data structure in a format in a manner such that it can be transmitted or stored and reconstructed later when needed.
Serializers are available in the Django REST Framework module. These are used to convert objects to the data types that can be understood by front-end frameworks and JavaScript. It can be used to deserialize the data, i.e., reconversion of parsed data to complex types after the incoming data has been validated.
Two serializers that are commonly used are:
- Model Serializer
- HyperLinkModelSerializer
Creation and Usage of Serializers
Creating a Serializer
To create a serializer, firstly we have to import the serializer class from the rest_framework module. After importing the class, we define the fields for a serializer just like we do in Django while creating a model or a form.
Example to illustrate the creation of a serializer:
# Importing the serializer class from rest_framework
from rest_framework import serializers
# Creating a Serializer
class comment_serializer(serializers.Serializer):
# Initializing required fields
created = serializers.DateTimeField( )
content = serializers.CharField(max_length = 250)
email = serializers.EmailField( )
An above-given example is one of the ways to create a Serializer for any particular object or entity that is based on required fields.
Serializers can be used for both, serializing and deserializing the data.
Using a Serializer to Serialize the Data
Now that the serializer named comment_serializer has been created, now it can be used to serialize comments. Now let us create a comment class to create an object of comment type that would be easy for our serializer to understand.
# Importing the datetime object
from datetime import datetime
# Creating a Class
class Comment(object):
def __init__(self, email, content, created = None):
self.created = datetime.now( ) or created
self.content = content
self.email = email
# Creating an object
comment = Comment(email = 'contentjtp.com', content = 'Daily basis work')
After creating the object of the comment type, we will try serializing this comment. To perform this operation following command has to be executed:
Python manage.py shell
Now run the following code in the python shell,
# Importing comment serializer
>>> from apis.serializers import comment_serializer
# Importing datetime for date and time
>>> from datetime import datetime
# Creating an object
>>> class Comment(object):
... def __init__(self, email, content, created = None):
... self.email = email
... self.content = content
... self.created = created or datetime.now()
...
# Creating a comment object
>>> comment = Comment(email = 'contentjtp.com', content = 'Daily basis work')
# Serializing the data
>>> serializer = comment_serializer(comment)
# Printing the serialized data
>>> serializer.data
What is ModelSerializer?
To create a serializer automatically we use ModelSerializer. This automatically created serializer contains the fields that correspond to the Model fields.
Some of the advantages of using ModelSerializer over a regular serializer are:
- The ModelSerializer automatically builds a set of fields for the user according to the model.
- Multiple validators such as unique_together, are automatically generated by it for the serializer.
- It comes with default implementations of “.update( )” and “.create( )”.
Syntax for ModelSerializer:
class NameOfSerializer(serializers.ModelSerializer):
class Meta:
fields = List of Fields
model = NameOfModel
Example to illustrate a ModelSerializer:
class SerializerForAccount(serializers.ModelSerializer):
class Meta:
fields = ['user_id', 'account_name', 'users', 'created']
model = Account
Note: By default, all the model fields initialized in the class will be mapped to an analogous serializer field.
What is HyperLinkModelSerializer?
Both, the ModelSerializer class and HyperLinkModelSerializer class are almost the same in every aspect, except in the case of representing relationships, i.e., ModelSerializer uses primary keys to represent relationships whereas HyperLinkModelSerializer uses hyperlinks to represent relationships.
While using HyperLinkModelSerializer, by default serializer will have a URL field instead of a primary key field. To represent the URL field, a HyperlinkedIdentityField serializer field will be used, and to represent any other relationship, the HyperlinkedRelatedField serializer field will be used.
The syntax for HyperLinkModelSerializer:
class NameOfSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
fields = List of Fields
model = NameOfModel
An example to illustrate HyperLinkModelSerializer:
class SerializerForAccount(serializers.ModelSerializer):
class Meta:
fields = ['user_id', 'account_name', 'users', 'created']
model = Account
Serializer Fields:
Name of Field | Description of Field |
EmailField | EmailField is used to store text representation and it also validates whether the text is a valid e-mail address or not. |
CharField | CharField is used to store text representation. |
RegexField | This field works as the name defines, i.e., it matches a string to be a particular regex or else throws an error. |
BooleanField | The BooleanField is used to wind up True or False values. |
NullBooleanField | It is a Boolean field that accepts values as True, False, or NULL. |
SlugField | It is a RegexField that checks the input against any particular pattern. |
URLField | It is also a RegexField that checks the input against a pattern that matches any URL. |
IntegerField | It is an integer field that checks the input against an int instance of Python. |
FloatField | It is a float field that checks the input against a float instance of Python. |
DecimalField | It is a decimal field that checks the input against a decimal instance of Python. |
DateField | This serializer field is used to represent the date. |
TimeField | This serializer field is used to represent time. |
IPAddressField | It is a field that checks whether the entered string is a valid IPv4 or IPV6 string or not. |
DateTimeField | This serializer field is used to represent the date and time together. |
DurationField | This serializer is used to represent duration. |
ChoiceField | This serializer field is like the CharField, but it checks for the input against a limited set of choices. |
MultipleChoiceField | This serializer field is like the CharField, but it checks for the input against a limited set of choices, it accepts input as a set of zero or a set of one or many values. |
ImageField | This serializer field is used to represent an image. It checks the content of a file uploaded against a known image format. |
FileField | This serializer field is used to represent a file. It validates the file according to Django’s standards. |
JSONField | This serializer field class is used to check whether the entered data structure is a valid JSON object or not. |
ListField | This serializer field checks the entered data against a list of objects. |
HiddenField | This serializer field does not depend upon the value entered by the user, it takes value from callable or default value. |
DictField | This serializer field checks the entered data against a dictionary of objects. |