Deserialization in Django REST Framework

Deserialization of data in Django REST framework

Gautamankul
3 min readMay 2, 2022

Rinu Gour TDS Editors Aman Kharwal

Deserialization in Django REST Framework

Hey, developers, today we’re going to learn how to do simple Deserialization in Django REST Framework.

We do not require much knowledge like the multi-talented brain power of Lucy for Deserialization of data in Django REST framework

Prerequisite

We only require some libraries for the Django REST framework.

  1. Django
  2. Django REST framework

Setup

We are using Virtualenv for project environment creation and in that project, we will change Json or XML into Complex data.

Here I am using Windows 10, so I am going use pip instead of pip3 for Ubuntu or other Linux distro .

Let’s get started.

$ virtualenv venv
$ ./venv/Scripts/activate
$ pip install django

Project setup are done now we need to create django project …………

$ django-admin startproject drfproject .
$ python manage.py startapp api
$ python manage.py runserver

It will show, Django default home page. Now we need to install djangorestframework package.

$ pip install djangorestframework

Everything are done now move to real stuff …….

  1. Fist we need to change settings.py file and register our third party app like below.
INSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','rest_framework',                 # for rest frame work'api',                            # local app]

2. What is deserialization ?

De-serialization allow to convert parsed data(JSON or XML) into complex data type after first validation of incoming data.

Deserialization in Django REST Framework

In deserialization three important aspects are most necessary ,these are following ..

  1. ByteIo
  2. JSONParser
  3. Data validations

A. ByteIo is a stream implementation using a memory byte buffer means it will change the incoming data stream

B. JSONParser change the Json data into python native data typed.

C. Before data saving ,must validated serialized dat using is_valid() method.

Note: Update and Create operation are responsible for Deserialization.

We have done Boring , explanation like do generally do move to real stuff.

3. create models for inserting data.

from django.db import models# Create your models here.class Student(models.Model):    name = models.CharField(max_length=200)
roll = models.IntegerField()
address = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.name

Now ,register that model into admin.py like below

from django.contrib import adminfrom .models import *# Register your models here.admin.site.register(Student)

4. Now we need to create serializers.py for creating model data into serialized data.

from rest_framework import serializersfrom api.models import Student
class StudentSerializer(serializers.Serializer):
name = serializers.CharField(max_length=200)
roll = serializers.IntegerField()
address = serializers.CharField(max_length=200)
def create(self, validated_data):
return Student.objects.create(**validated_data)

Note: In serializers.py have one default method create it is responsible for creating validate data serializes.

5. Next is implement logic to convert complex data which is coming from frontend (Android) and save into models .In views.py The gist url is here.

https://gist.github.com/Gautamankulofficial1/9624933c4543b8b700b00c735c88a326

Note : In above code snippets createstudent method is responsible for deserializations.

6. Mapping the Url for the endpoints….

In urls.py of main project folder.

from django.contrib import admin
from django.urls import path
from api import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api/<int:id>', views.getStudent ,name='Student'),
path('api/createstudent',views.createStudent ,name='createStudent'),
]

7. Now, create a separate file for sending complex data .

Note :

  • It may be a Android app or other web app.
  • In that article i am creating root directory android.py file
Deserialization in Django REST Framework
  • in android.py
import requests
import json
URL = 'http://127.0.0.1:8000/api/createstudent'data = {
"name": "Rahul",
"roll": 104,
"address": "Noida",
}
jdata =json.dumps(data)r = requests.post(url= URL, data=jdata)data = r.json()print(data)

Shhh! Now everything are done we gone run this projects.

Note : *

  • Open two terminal
  • first one run python manage.py runserver
  • sencond one python android.py
  • Then you got your data in terminal

Thank you for reading! Hope this helps you follow me for more article.

--

--

Gautamankul

A Software Developer Engineer & Entrepreneur and along with i am a Buddhist.