Creating and Using Serializers - Django REST Framework
Last Updated :
10 Sep, 2021
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. 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. The serializers in REST framework work very similarly to Django's Form and ModelForm classes.
To check how to setup Django RESt Framework and create a API visit - How to Create a basic API using Django Rest Framework ?
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.
Example
Python3
# 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.
Python3
# import datetime object
from datetime import datetime
# create a class
class Comment(object):
def __init__(self, email, content, created = None):
self.email = email
self.content = content
self.created = created or datetime.now()
# create a object
comment = Comment(email ='[email protected]', 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='[email protected]', content='foo bar')
# serialize the data
>>> serializer = CommentSerializer(comment)
# print serialized data
>>> serializer.data
Now let's check output for this,
We can convert this data to JSON or XML format using Python's inbuilt functions or rest framework's parsers.
Python3
# import JSON Renderer
from rest_framework.renderers import JSONRenderer
# convert data to JSON
json = JSONRenderer().render(serializer.data)
Using Serializer to deserialize data
Deserialization is similar to Serialization. It means to convert the data from JSON format to a given data type. First we parse a stream into Python native datatypes... (define which datatype to deserialize to....)
First we need to convert this json data back to data that can be understood by the serializer for deserializing,
Python3
import io
from rest_framework.parsers import JSONParser
stream = io.BytesIO(json)
data = JSONParser().parse(stream)
and Now let's deserialize the data back to its original state
Python3
serializer = CommentSerializer(data = data)
serializer.is_valid()
# True
serializer.validated_data
Let's check output and if data has been deserialized -
Similar Reads
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
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
Date and time 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
7 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
Boolean 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
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
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
How to Create a basic API using Django Rest Framework ?
Django REST Framework is a wrapper over the default Django Framework, basically used to create APIs of various kinds. There are three stages before creating an API through the REST framework, Converting a Model's data to JSON/XML format (Serialization), Rendering this data to the view, and Creating
3 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 serializ
15+ min read