<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Palak Rathi on Medium]]></title>
        <description><![CDATA[Stories by Palak Rathi on Medium]]></description>
        <link>https://medium.com/@palakrathiiit?source=rss-6e8366cfe50b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*98TjI6kUHzNmsM7p</url>
            <title>Stories by Palak Rathi on Medium</title>
            <link>https://medium.com/@palakrathiiit?source=rss-6e8366cfe50b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:20:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@palakrathiiit/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[All about Serialization and Deserialization.]]></title>
            <link>https://medium.com/@palakrathiiit/all-about-serialization-and-deserialization-edaec1b0dfae?source=rss-6e8366cfe50b------2</link>
            <guid isPermaLink="false">https://medium.com/p/edaec1b0dfae</guid>
            <dc:creator><![CDATA[Palak Rathi]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 09:56:34 GMT</pubDate>
            <atom:updated>2025-02-12T09:56:34.473Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why this post?</h3><p>When I started working with Django REST Framework (DRF), one of the biggest challenges I faced was understanding <strong>serialization and deserialization</strong> — how to convert Django models into JSON data and vice versa. There were multiple ways to achieve this, and each tutorial I found approached it differently.</p><p>After experimenting and troubleshooting, I finally understood the difference between <strong>Serializer</strong> and <strong>ModelSerializer</strong>, when to use each, and how <strong>deserialization</strong> plays a crucial role in handling incoming data. Since many developers face the same confusion, I decided to share my experience in a structured and easy-to-understand way.</p><p>This post will walk you through:<br>✅ What serialization and deserialization are.<br>✅ What serialization and deserialization in Django REST Framework (DRF) are and why we need them.<br>✅ Understanding Serializer and ModelSerializer in Django REST Framework.<br>✅ When to use which, along with real-world use cases.</p><h3>What Serialization and Deserialization are</h3><h4>What is Serialization?</h4><p>Serialization is the process of converting an object (such as a Python dictionary, class instance, or any data structure) into a format that can be easily stored or transmitted. Common formats include JSON, XML, and binary formats.</p><h4>What is Deserialization?</h4><p>Deserialization is the opposite process, where the serialized data is converted back into an object. This allows data to be reconstructed and used within a program.</p><h3>Real-Life Example: Sending a Parcel</h3><p>Imagine you want to send a gift (your object) to a friend who lives in another city. The process can be compared to serialization and deserialization:</p><ol><li><strong>Serialization (Packing the Object)</strong></li></ol><ul><li>You <strong>wrap</strong> the gift in a box.</li><li>You <strong>label</strong> it with the recipient’s details (making it readable by delivery services).</li><li>The gift is now in a <strong>transportable format</strong> (like JSON or binary).</li></ul><p>2. <strong>Sending the Parcel (Storing/Transmitting Data)</strong></p><ul><li>The parcel is <strong>transported</strong> via a delivery service (like an API request or file storage).</li><li>The recipient receives it in the same packed format.</li></ul><p>3. <strong>Deserialization (Unpacking the Object)</strong></p><ul><li>Your friend <strong>opens</strong> the package.</li><li>The original gift (object) is now <strong>retrieved and ready for use</strong>.</li></ul><h3>What is Serialization and Deserialization in DRF?</h3><p><strong>Serialization</strong> and <strong>deserialization</strong> are two key processes in Django REST Framework (DRF) that allow data to be exchanged between the backend and frontend in a structured way.</p><ul><li><strong>Serialization</strong>: Converts Django model instances (Python objects) into JSON data, making it easy to send data via APIs.</li><li><strong>Deserialization</strong>: Converts incoming JSON data into Django model instances, allowing the backend to store or process the data.</li></ul><h3>Why Do We Need Them?</h3><p>Modern web applications, mobile apps, and frontend frameworks like React or Angular require <strong>JSON-formatted data</strong> to communicate with the backend. Since Django models store data in <strong>Python object format</strong>, we need <strong>serialization</strong> to convert it into JSON. Similarly, when data is received from a client, <strong>deserialization</strong> is needed to convert it back into a Django model for database storage.</p><h3>Example of Serialization and Deserialization in Django REST Framework (DRF)</h3><p>Let’s go step by step and understand how <strong>serialization and deserialization</strong> work in DRF.</p><h3>Step 1: Create a Django Model</h3><pre>1. from django.db import models  <br>2.<br>3. class User(models.Model):  <br>4.     name = models.CharField(max_length=100)  <br>5.     email = models.EmailField(unique=True)   </pre><p>Now, let’s understand this code line by line.</p><p><strong>Line 1:</strong> We import models from Django&#39;s ORM.</p><p><strong>Line 3-4:</strong> We define the User model with name and email fields.</p><p><strong>Line 5:</strong> The email field is set to unique=True, ensuring that no two users have the same email.</p><h3>Step 2: Create a Serializer (Converting Between JSON &amp; Python Objects)</h3><pre>1. from rest_framework import serializers  <br>2. from .models import User <br>3. <br>4. class UserSerializer(serializers.ModelSerializer):  <br>5.   class Meta:  <br>6.       model = User  <br>7.       fields = &#39;__all__&#39;  </pre><p><strong>Line 1–2:</strong> Import the necessary modules.</p><p><strong>Line 4: </strong>We create a class UserSerializer which extends the serializer.</p><p><strong>Line 5:</strong> The Meta class is referenced during the construction of the form/object instance before the class definition itself.</p><p><strong>Line 6</strong>: Tells the model to be used.</p><p><strong>Line 7:</strong> We include <strong>all fields</strong> from the model (name, email).</p><h3>Step 3: Serialization — Convert Model to JSON (Read Data)</h3><pre>1. from rest_framework.response import Response  <br>2. from rest_framework.views import APIView  <br>3. from .models import User  <br>4. from .serializers import UserSerializer  <br>5. <br>6. class UserView(APIView):<br>7.    def get(self, request):  <br>8.        users = User.objects.all()  <br>9.        serializer = UserSerializer(users, many=True)   <br>10.        return Response(serializer.data) </pre><p><strong>Line 1–4:</strong> Import necessary modules.</p><p><strong>Line 6:</strong> Defines a class UserView that extends APIView.</p><ul><li>This means it can handle RESTful API methods like <strong>GET, POST, PUT, DELETE</strong>.</li></ul><p><strong>Line 7:</strong> Defines the get method to handle <strong>GET requests</strong>.</p><ul><li>This method is called when a client (like Postman or a frontend) requests user data.</li></ul><p><strong>Line 8:</strong> Fetches all User records from the database.</p><p><strong>Line 9:</strong> Converts (serializes) the queryset into JSON using UserSerializer.</p><p><strong>Line 10:</strong> Returns the serialized JSON response to the frontend.</p><p><strong>Example API Response (JSON)</strong></p><pre>[<br>    {<br>        &quot;id&quot;: 1,<br>        &quot;name&quot;: &quot;Alice&quot;,<br>        &quot;email&quot;: &quot;alice@example.com&quot;<br>    },<br>    {<br>        &quot;id&quot;: 2,<br>        &quot;name&quot;: &quot;Bob&quot;,<br>        &quot;email&quot;: &quot;bob@example.com&quot;<br>    }<br>]</pre><h3>Step 4: Deserialization — Convert JSON to Model (Save Data)</h3><pre>1. class UserCreateView(APIView):  <br>2.  def post(self, request):  <br>3.      serializer = UserSerializer(data=request.data) <br>4.<br>5.        if serializer.is_valid():  <br>6.          serializer.save()   <br>7.          return Response({&quot;message&quot;: &quot;User created successfully!&quot;}, status=201)  <br>8.       <br>9.      return Response(serializer.errors, status=400)  </pre><p><strong>Line 3:</strong> Takes incoming JSON data (request.data) and <strong>deserializes</strong> it.</p><p><strong>Line 5:</strong> Checks if the data is valid using serializer.is_valid().</p><p><strong>Line 6:</strong> If valid, serializer.save() creates a new User entry in the database.</p><p><strong>Line 9:</strong> If invalid, it returns validation errors.</p><p>✅ <strong>Example API Request</strong></p><pre>{<br>    &quot;name&quot;: &quot;Charlie&quot;,<br>    &quot;email&quot;: &quot;charlie@example.com&quot;<br>}</pre><p>✅ <strong>Example API Response (Success)</strong></p><pre>{<br>    &quot;message&quot;: &quot;User created successfully!&quot;<br>}</pre><p>❌ <strong>Example API Response (Validation Error — Email Missing)</strong></p><pre>{<br>    &quot;email&quot;: [&quot;This field is required.&quot;]<br>}</pre><h3>Understanding Serializer and ModelSerializer in Django REST Framework (DRF)</h3><p>When working with Django REST Framework (DRF), one of the most important concepts to understand is how to perform serialization. DRF provides two primary classes for handling serialization: Serializer and ModelSerializer.</p><h3>1️⃣ What is a Serializer?</h3><p>A Serializer in DRF works similarly to Django Forms,it allows you to define fields explicitly and control how data is converted between Python objects and JSON. It provides full flexibility but requires manual field definitions.</p><h3>Example of a Serializer:</h3><pre>1.  from rest_framework import serializers<br>2.  <br>3.  class ProductSerializer(serializers.Serializer):  <br>4.      id = serializers.IntegerField(read_only=True)  <br>5.      name = serializers.CharField(max_length=255)  <br>6.      price = serializers.DecimalField(max_digits=10, decimal_places=2)  <br>7.      description = serializers.CharField()<br>8.  <br>9.      def create(self, validated_data):<br>10.         return Product.objects.create(**validated_data)<br>11.  <br>12.     def update(self, instance, validated_data):<br>13.         instance.name = validated_data.get(&#39;name&#39;, instance.name)<br>14.         instance.price = validated_data.get(&#39;price&#39;, instance.price)<br>15.         instance.description = validated_data.get(&#39;description&#39;, instance.description)<br>16.         instance.save()<br>17.         return instance</pre><p><strong>Line 1</strong>: We import serializers from Django REST Framework.</p><p><strong>Line 3:</strong> We create a class ProductSerializer which extends serializers.Serializer.</p><p><strong>Lines 4–7:</strong> We define <strong>serializer fields</strong> that determine how model data is converted to JSON and vice versa.</p><ul><li><strong>Line 4:</strong> Defines an id field as an integer that is read-only.</li><li><strong>Line 5:</strong> Defines a name field as a character string with a maximum length of 255.</li><li><strong>Line 6:</strong> Defines a price field as a decimal with a maximum of 10 digits and 2 decimal places.</li><li><strong>Line 7:</strong> Defines a description field as a simple text field.</li></ul><p><strong>Line 9–10:</strong> The create method handles creating a new Product instance using validated data.</p><p><strong>Lines 12–17:</strong> The update method updates an existing Product instance while keeping old values if new ones are not provided.</p><p><strong>Key Takeaways:</strong><br>1. We manually define each field.<br>2. We implement create() and update() methods to handle data persistence.<br>3. Provides <strong>maximum control</strong> but requires more boilerplate code.</p><h3>2️⃣ What is a ModelSerializer?</h3><p>A ModelSerializer is a shortcut that automatically creates serializer fields based on a Django model. It reduces boilerplate code and follows DRF&#39;s <strong>&quot;convention over configuration&quot;</strong> approach.</p><h3>Example of a ModelSerializer:</h3><pre>1. from rest_framework import serializers<br>2. from .models import Product<br>3.<br>4. class ProductSerializer(serializers.ModelSerializer):<br>5.     class Meta:<br>6.         model = Product <br>7.         fields = &#39;__all__&#39; </pre><p><strong>Line 1</strong>: We import serializers from Django REST Framework.</p><p><strong>Line 2: </strong>This imports the Product model from the current app&#39;s models.py file.</p><p><strong>Line 4: Defines </strong><strong>ProductSerializer</strong>, inheriting from ModelSerializer to automatically generate fields based on the Product model.</p><p><strong>Line 5:</strong> The Meta class is referenced during the construction of the form/object instance before the class definition itself.</p><p><strong>Line 6</strong>: Tells the model to be used.</p><p><strong>Line 7:</strong> We include <strong>all fields</strong> from the model (id, price, name, description).</p><p><strong>Key Takeaways:</strong><br>1. Automatically generates fields from the model.<br>2. No need to define create() and update() methods—they are handled internally.<br>3. Best when working directly with Django models.</p><h3>When to use which, along with real-world use cases.</h3><h3>1. When to Use ModelSerializer:</h3><ul><li><strong>Use </strong><strong>ModelSerializer when you are working with Django models and want DRF to automatically generate the serializer fields based on the model.</strong></li><li><strong>Ideal for CRUD operations</strong>: It’s a good choice when you want to quickly create, read, update, and delete model data without much customization.</li><li><strong>Minimize boilerplate code</strong>: If your API endpoints closely reflect your database models, ModelSerializer is the best choice as it reduces the amount of code you need to write.</li></ul><h4>Real-World Use Cases for ModelSerializer:</h4><ol><li><strong>E-commerce Application (Product API):</strong></li></ol><ul><li>When you have a Product model in your database and need to expose a simple API to list, add, update, and delete products. Using ModelSerializer will automatically handle all fields and CRUD operations.</li></ul><p>Example:</p><pre>class ProductSerializer(serializers.ModelSerializer):<br>    class Meta:<br>        model = Product<br>        fields = &#39;__all__&#39;</pre><h3>2. When to Use Serializer:</h3><ul><li><strong>Use </strong><strong>Serializer when you need more control over the fields, validation, or serialization logic, especially when you are not working directly with a Django model or when you need custom behavior.</strong></li><li><strong>Ideal for non-model data</strong>: If you’re dealing with data that isn’t mapped to a Django model (e.g., data from an external API, form data, etc.), then Serializer is a better option.</li><li><strong>Custom validation or processing</strong>: If you need to add custom validation, complex logic, or need to combine or transform fields, Serializer gives you the flexibility to do so.</li></ul><h4>Real-World Use Cases for Serializer:</h4><ol><li><strong>User Registration with Custom Validation:</strong></li></ol><ul><li>When you need to accept custom user data (e.g., password confirmation, complex validation for username), Serializer allows you to control the validation logic.</li></ul><p>Example:</p><pre>class UserRegistrationSerializer(serializers.Serializer):<br>    username = serializers.CharField(max_length=100)<br>    password = serializers.CharField(write_only=True)<br>    password_confirmation = serializers.CharField(write_only=True)<br><br>    def validate(self, data):<br>        if data[&#39;password&#39;] != data[&#39;password_confirmation&#39;]:<br>            raise serializers.ValidationError(&quot;Passwords do not match&quot;)<br>        return data</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edaec1b0dfae" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>