Instagram
youtube
Facebook
Twitter

Deserialization in Django REST Framework

In this tutorial, we'll learn about deserialization in Django REST Framework (DRF). Deserialization is the process of converting serialized data, such as JSON, back into complex data types like querysets or model instances.

Deserialization in Django REST Framework:

  • Deserialization in DRF is the reverse process of serialization.

  • It takes serialized data, such as JSON or other content types, and converts it into Python objects that can be easily worked with in the Django application.

Let's assume we have the same Students model as used in the previous example:

Next, we'll create a new file called serializers.py and define the StudentsDeserializer serializer class.

serializers.py

from rest_framework import serializers
from .models import Students

class StudentsDeserializer(serializers.ModelSerializer):
    class Meta:
        model = Students
        fields = ['Name', 'Roll', 'City']

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

In the StudentsDeserializer class, we define the Meta class with the model attribute set to Students, indicating that this serializer is associated with the Students model for deserialization. We specify the fields attribute to include only the fields that can be deserialized from the incoming data.

The create() method is responsible for creating a new instance of the Students model based on the validated data. It will be used during the deserialization process to create new objects.

Now, let's move on to the views.py file, where we'll use the StudentsDeserializer to handle the deserialization of incoming data.

views.py

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .serializers import StudentsDeserializer
from rest_framework.parsers import JSONParser

@csrf_exempt
def create_student(request):
    if request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = StudentsDeserializer(data=data)

        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)

        return JsonResponse(serializer.errors, status=400)

This code defines a Django view function named `create_student` to handle POST requests. The view uses `@csrf_exempt` decorator to bypass CSRF protection for simplicity. 

When a POST request is received, the function extracts JSON data from the request using `JSONParser`. It then creates an instance of `StudentsDeserializer` with the extracted data for deserialization.

If the deserialization is successful (i.e., the data is valid), the student object is saved to the database, and the serialized data is returned as a JSON response with a status code of 201 (Created).

If the deserialization fails (i.e., the data is invalid), the serializer errors are returned as a JSON response with a status code of 400 (Bad Request).

Now, let's write a simple script to send a POST request with the JSON data.

send.py

import requests

data = {
    "Name": "William",
    "Roll": 123456,
    "City": "Indore"
}

response = requests.post('http://localhost:8000/create_student/', json=data)

print(response.json())

When we run 'send.py' script it will send a POST request to our Django server with the JSON data representing a new student. The server will deserialize the JSON data, create a new student object, and return the serialized student data as a JSON response.

Now, let's check new object is created in our admin or not.