What is a Serializer?

A Serializer takes a data that exists on the server, parses data from complex types into a format (JSON or XML) that can be read by other technologies.

Or,

A serializer is a framework that allows complex data such as ‘querysets’ and model instances to be converted to native Python data types. Then, we can easily render these into JSON, XML, or other content types.

There Two types of Serializers in Django.

  • serializers.Serializer &
  • serializers.ModelSerializer

The Serializers and ModelSerializers work in a way similar to Forms and ModelForms. Unlike forms, they are not constrained to dealing with HTML output and form encoded input.

We will discuss both types.

serializers.Serializer

Serializer class is more customizable. But a little messy to use. On the other hand, ModelSerializers are less customizable but much simpler to set up and use. You can see it here.

Example:


from rest_framework import serializers


class PersonSerializer(serializers.Serializer):
    first_name = serializers.CharField(max_length=255)
    last_name = serializers.CharField(max_length=255)


    def create(self, validated_data):
        # perform person object creation
        return person

    def update(self, instance, validated_data):
        # perform object update
        return object

After that, you can create or update instances by calling is_valid() to validate the data and save() to create or update an instance:


serializer = PersonSerializer(**data)
## to validate data, mandatory before calling save
serializer.is_valid()
serializer.save()

Let’s see an example in shell. run ‘python manage.py shell’


>>> from first_app.serializers import PersonSerializer >>> from first_app.models import Person >>> >>> person = Person(first_name='arafat',last_name='yeasir') >>> person.save() >>> serializer = PersonSerializer(person) >>> serializer.data {'first_name': 'arafat', 'last_name': 'yeasir'}

More Arguments that can be used in Serializers class fields.

Argument Description
read_only Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization
write_only Set this to True to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.
required Setting this to False also allows the object attribute or dictionary key to be omitted from output when serializing the instance.
default If set, this gives the default value that will be used for the field if no input value is supplied.
allow_null Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value.
label A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.
help_text A text string that may be used as a description of the field in HTML form fields or other descriptive elements.
initial A value used for pre-populating the value of HTML form fields.

You can see more fields and arguments of Serializers here.

serializers.ModelSerializer

A ModelSerializer is just a regular Serializer, except that:

  • A is_valid(self, ..) method can tell if the data is sufficient and valid to create/update a model instance.
  • A save(self, ..) method, which knows how to create or update an instance.
  • A create(self, validated_data, ..) method which knows how to create an instance. We can override this method to customize the update behaviour.
  • An update(self, instance, validated_data, ..) method which knows how to update an instance. We can override this method to customize the update behaviour.

Syntax:

class SerializerName(serializers.ModelSerializer):
    class Meta:
        model = ModelName
        fields = List of Fields or ‘__all__’

Example:

class PersonSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Person
        # or '__all__'
        fields = ['first_name','last_name']

Django automatically includes all model fields in the serializer and creates the create and update methods.

Using Serializers in Class-Based Views

In Django’s CBVs, we can integrate serializers by setting serializer_class attribute so that the serializer becomes available to the view:


from rest_framework import generics class PersonAPIView(generics.ListAPIView): queryset = Person.objects.all() serializer_class = PersonSerializer

We can also define the get_serializer_class() method:


from rest_framework import generics


class PersonAPIView(generics.ListAPIView):
    queryset = Person.objects.all()
   
    def get_serializer_class(self):

        return PersonSerializer

There are other methods in CBVs that interact with serializers. For example, get_serializer() returns an already-instantiated serializer, while get_serializer_context() returns the arguments you’ll pass to the serializer when creating its instance.

+ posts

Author | Python-Django Developer

+ posts

Full-stack Developer (Python | Django | React | React-Native | Angular | Vue)