Serializers in Django

1 Min. Read
May 20, 2021

What is Serializer

Django REST Framework (DRF) is a one of the most popular tool for creating very flexible REST APIs. It has a lot of built-in features like pagination, search, filters, and many other things developers don’t like to worry about. And it also lets developers to easily customize everything and the API make it work accordingly. One family of classes DRF is Serializers. Serializers are used to convert the data sent in a HTTP request to a Django object and a Django object to a valid response data. Serializers interact directly with django model in order to convert an object to valid response format.

Declaring Serializers

First of all we create a simple object

1
2
3
4
5
6
7
8
from datetime import datetime

class Student:
    def __init__(self, email, created=None):
        self.email = email
        self.created = datetime.now()

student = Student(email='[email protected]')

After that we create a serializer class StudentSerializer

1
2
3
4
5
from rest_framework import serializers

class StudentSerializer(serializers.Serializer):
    email = serializers.EmailField()
    created = serializers.DateTimeField()

Creating a simple Serializer which stores student email and created date

Serializing objects

1
2
3
4
serializer = StudentSerializer(student)
serializer.data

{‘email’:’[email protected]’,’created’:’2021-05-20’}

Here we are passing the student object that we have created previously which now validates and saves the data

Another way is we directly take data from request.data

1
2
3
4
5
6
serializer = StudentSerializer (data=request.data)
serializer.is_valid()
 True

serializer.validated_data
{‘email’:’[email protected]’,’created’:’2021-05-20’}

Here we are calling the same serializer and in place of data, we are passing the data we get from request.data.

Saving instances

We can save instances using create() and update() methods

1
2
3
4
5
6
7
8
9
10
11
12
class StudentSerializer (serializers.Serializer):
    email = serializers.EmailField()
    created = serializers.DateTimeField()

    def create(self, validated_data):
        return Student.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.email = validated_data.get('email', instance.email)
        instance.created = validated_data.get('created', instance.created)
        instance.save()
        return instance

Validation

1
2
3
4
5
serializer = StudentSerializer(data={'email': 'rishav'})
serializer.is_valid()
False
serializer.errors
{'email': ['Enter a valid e-mail address.']}

Before saving data we use serializer.is_valid() to verify if the data is valid as per the model object fields and its contents. We can also use

1
serializer.is_valid(raise_exception=True)

to raise an exception if data is invalid.

In this way we can simply user serializer and convert our model object to readable format.