How to Use Serializers in Django Rest Framework?

Hi Dev,
Today, how to serializers data in django rest framework is our main topic. This article goes in detailed on how to use serializers in django rest framework. you will learn serializers in django rest framework. This tutorial will give you simple example of django rest framework serializer example.
The Django REST Framework's serializers are in charge of transforming objects into data formats that front-end frameworks and javascript can understand. After validating the incoming data, the serializer also offers deserialization, which enables parsed data to be transformed back into complicated types. The REST framework's serializers operate very similarly to the Form and Model Form classes in Django. ModelSerializer and HyperLinkedModelSerializer are the two main serializers that are most frequently used.
Here i will give you we will help you to give example of how to serializers data in django rest framework. So let's see the bellow example:
Step 1: Create a Project
In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:
django-admin startproject exampleStep 2: Create a App
cd example django-admin startapp core
Step 3: Install required library
Install Django and its prerequisites:
pip install djangorestframework
Step 4: Update settings.py
Next, you need to add it in the settings.py file as follows:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'rest_framework' ]
Step 5: Creating the Serializers
In this step, Similar to constructing a form or model in Django, creating a basic serializer requires importing the serializers class from the rest framework and defining the serializer's fields.
core/serializers.pyfrom rest_framework import serializers class PostSerializer(serializers.Serializer): title = serializers.CharField(max_length = 255) description = serializers.CharField() created = serializers.DateTimeField()
Open your python django shell following through command..
python manage.py shell
Now, put the below code in your django shell.
# import comment serializer >>> from core.serializers import PostSerializer # import datetime for date and time >>> from datetime import datetime # create a object class Post(object): def __init__(self, title, description, created=None): self.title = title self.description = description self.created = created or datetime.now() # create a comment object >>> post = Post(title='Django Image Upload', description='Django Image Upload Example') # serialize the data >>> serializer = PostSerializer(post) # print serialized data >>> serializer.dataOutput
{ 'title': 'Django Image Upload', 'description': 'Django Image Upload Example', 'created': '2022-12-20T04:50:15.535741Z' }
I Hope It will help you....