Python

How to use Django Serializers

Serializer is used in Django to convert the model instances or querysets into python supported data types that can be easily rendered into JSON, XML, or other formats. The deserialization can also be done by serializers to get back the original data from the serialized data. This feature is available in Django REST Framework. So, the users have to install this framework to use the serializers. Any webpage of the website may contain HTML, CSS, and data from the database tables. But the API does not understand these types of content, and it can understand the raw data only, that is, JSON data. How the serializers can be used to convert the model instance into JSON format has shown in this tutorial.

Prerequisites:

Before practicing the script of this tutorial, you have to complete the following tasks.

  1. Install the Django version 3+ on Ubuntu 20+ (preferably)
  2. Create a Django project
  3. Run the Django server to check the server is working properly or not.

Setup a Django app for Serializers:

Run the following command to create a Django app named serialapp.

$ python3 manage.py startapp serialapp

Run the following command to create the user for accessing the Django database. If you have created the user before, then you don’t need to run the command.

$ python3 manage.py createsuperuser

Run the following command to install Django REST Framework.

$ pip3 install djangorestframework

Add the rest_framework and app name in the INSTALLED_APP part of the settings.py file.

INSTALLED_APPS = [
         ….
     'rest_framework',
     'serialapp'
]

Create a model for the database table:

Open the models.py file from the serialapp folder and add the following script to define the structure of customers tables. Customer class is defined to create a table named customers with name, address, email, contact_no, and created fields. Here, name, email, and contact_no fields will store character data, the address field will store the text data, and created field will store the DateTime data.

models.py

# Import the models module
from django.db import models

# Define the model class for the customers table
class Customer(models.Model):

    name = models.CharField(max_length=100)
    address = models.TextField()
    email = models.CharField(max_length=50)
    contact_no = models.CharField(max_length=20)
    created = models.DateTimeField(auto_now_add=True)

Run the makemigrations command to create a new migration based on the changes made by the models.

$ python3 manage.py makemigrations serialapp

Run the migrate command to execute the SQL commands and create all tables in the database defined in the models.py file.

$ python3 manage.py migrate

Modify the content of the admin.py file with the following content. Here, the Customer class of the models is registered by using the register() method to display the customers tables in the Django administration dashboard.

admin.py

# Import admin module
from django.contrib import admin
# Import the Customer model
from .models import Customer
# Register the customer model
admin.site.register(Customer)

urls.py

from django.urls import path
from django.contrib import admin

urlpatterns = [
    # Define the path for admin
    path('admin/', admin.site.urls),
]

Add records into the table:

Open the Django Administration page and add some records into the customers table displayed to the browser in JSON format. Here, three records have been inserted.

Modify the views.py:

Open the views.py file from the serialapp and replace the content with the following script. CustomerList class is defined to serialize all the customers’ records and return the data to the browser in JSON format. CustomerDetail class is defined to serialize the particular customer record based on the ID value and return the browser’s data in JSON format. CustomerSerializer is a serializers file that has been created in the next part of this tutorial.

views.py

# Import generics from the Django REST Framework
from rest_framework import generics

# Import Customer model
from .models import Customer

# Import CustomerSerializer from serializers
from .serializers import CustomerSerializer

# Define class to convert all records of the customers table into JSON
class CustomerList(generics.ListCreateAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer

# Define class to convert the particular record of the customers table into JSON
class CustomerDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer

Create Serializer:

Create serializers.py file in the same location of the views.py file with the following script. ModelSerializer class is used here to create CustomerSerializer class that returns the serializers class with the fields of the Customer model. The Customer model fields that will be converted into JSON format are mentioned in the Meta class.

serializers.py

# Import serializers module from Django REST Framework
from rest_framework import serializers
# Import Customer model
from .models import Customer

# Define the custom serializers class to convert the Customer model fields into JSON
class CustomerSerializer(serializers.ModelSerializer):

    class Meta:
        model = Customer
        fields = ('id', 'name', 'address', 'email', 'contact_no')

Modify the urls.py file:

Modify the content of the urls.py file with the following script. In the script, the ‘customers/‘ path is defined to display all records of the customers table in JSON format, and the ‘customers/<int:pk>/‘ path is defined to display the particular data of the customers table in JSON format based on ID value.

urls.py

# Import admin module
from django.contrib import admin
# Import path and include module
from django.urls import path
# Import the views
from serialapp import views
# Import format_suffix_patterns from Django REST Framework
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = [
    # Define the path for admin
    path('admin/', admin.site.urls),
    # Define the path to get all customers data in JSON format
    path('customers/', views.CustomerList.as_view()),
    # Define the path to get the particular customer data based on ID in JSON format
    path('customers//', views.CustomerDetail.as_view()),


]
urlpatterns = format_suffix_patterns(urlpatterns)

All records of the customers table will be shown in JSON format if the following URL will execute.

 

http://localhost:8000/customers

The record of the second customer will be shown in JSON format if the following URL executes.

http://localhost:8000/customers/2

Conclusion:

The use of serializers in the Django application to convert the model instance into JSON format has shown in this tutorial by using a simple script. The Django users will understand the purpose of using serializers and apply them in their application if required after reading this tutorial.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.