Django Serializer and how it works

Serializer is a Class in which we will use serializers.ModelSerializer as input to class for getting required data,

The main imports for the Serializer class are:

from rest_framework import serializers

By importing this class from rest_framework we have to pass them into our Serializer class as below:

class Serializerclassname(serializers.ModelSerializer):

In this class, we have to call the class Meta: in which we write a modal name and required fields as output.

Example:

from rest_framework import serializers
class Serializerclassname(serializers.ModelSerializer):
class Meta:
        model = ModalName
        fields = ['id','name']

Calling Serializer from code:

import serializer to the page you required firstly from the serializer page or where we wrote that serializer,

Then:

modal_list=modal.objects.filter(user_id=request.user_id,is_exists=1)
modal_list_data=Serializerclassname(modal_list, many = True).data

The Above serializer will return a serialized object containing the id and name.

Working of Serializer :

It works for both list and single data but returns the list data only,

It takes the input we pass to it and makes and loop and checks the data from the modal we mentioned in the serializer by comparing them it will return only fields that are mentioned in the metaclass.

So, the Process is it gets a single item but by its speed, it just combines the whole data we required and returns it as Serialized Data.

Sign In or Register to comment.