Serializers Advance

Learn via video courses
Topics Covered

Overview

Serializers enable the conversion of complex data like model instances and query sets into the native data types of Python. The shortcut is provided by the ModelSerializer class for making the serializers that work with the QuerySets and model instances.

Introduction to Serializers

Serializers enable the conversion of complex data like model instances and query sets into the native data types of Python. So that the rendering of the data into other content types, or in XML, JSON becomes easy. Deserialization is also provided by the serializers, after the incoming data validation deserialization allows the conversion of parsed data again into complex types. The working of the REST framework serializers and Form and ModelForm classes of Django is very similar. A generic and powerful way is provided by the Serializer class for controlling your response output and a useful shortcut is provided by the ModelSerializer class for making the Serializers Advance in Django which works with the QuerySets and model instances.

Creating and Using Serializers

Basic Serializer Creation

Importing the serializer class of the rest_framework is required for basic serializer creation. And for a serializer, fields are defined in a way similar to the Django model or form creation.

In this way, serializers can be declared based on the needed fields for any specific object or entity. Serializers Advance in Django is used for both serializing and deserializing the data.

Using Serializer to serialize data

For example or a list of examples of serialization, ExampleSerializer can be used. And again serializer class use looks very similar to the form class use. First of all, for object creation of the example type create an Example class.

Creation of the object is done. Now we will run the following commands and try to do the serialization of the object example.

Python manage.py shell

Now write the commands written below one by one

ModelSerializer

The shortcut is provided by the ModelSerializer class which enables automatic serializer class creation. And it has fields that correspond to the field of the model. Both the regular Serializer class and ModelSerializer class are the same, except

  • Based on the model, the field set is generated automatically by the ModelSerializer class.
  • validators like the unique_together validator is generated automatically for the serializer by the ModelSerializer class.
  • Simple default implementation of .update() and .create() is included in the ModelSerializer class.

Syntax for creating ModelSerializer:

Example: ModelSerializer of the above Example model is created by writing the following code:

Mapping of all the class model fields and respective serializer fields is done by default.

HyperLinkedModelSerializer

HyperlinkedModelSerializer and the ModelSerializer class are similar to each other except that instead of primary keys, hyperlinks are used by the HyperlinkedModelSerializer for relationship representation. Instead of a primary key, a URL field is included by the serializer by default. The HyperlinkedIdentityField serializer field represents the URL field and the HyperlinkedRelatedField serializer field represents the model relationships.

Syntax for creating HyperLinkedModelSerializer:

Example: ModelSerializer of the above Example model is created by writing the following code:

Serializer Fields

Fields used for Serializers Advance in Django are given below:

BooleanField: To wrap true or false values, Boolean fields are used.

NullBooleanField: A Null Boolean field is a type of field in which true, false, and null are allowed.

CharField: To store the representation of text, we used CharField.

EmailField: Just like CharField, EmailField is used to store the representation of text. But it is also used for validating whether the text has a valid email address or not.

RegexField: As suggested by its name, RegexField is used for matching strings with the specific regex, and displaying errors if the string does not match.

URLField: We can define URLField as a RegexField. It checks the input with the matching pattern of the URL.

SlugField: SludField also works like RegexField. It checks the input with a pattern such as [a-zA-Z0-9_-]+.

IPAddressField: To check whether the input is a proper IPv4 or IPv6 string, IPAddressField is used.

IntegerField: IntegerField is a type of field that is used for checking the input with an int instance of Python.

FloatField: FloatField is a type of field that is used for checking the input with a float instance of Python.

DecimalField: DecimalField is a type of field that is used for checking the input with a decimal instance of Python.

DateTimeField: DateTimeField is a serializer field for the representation of the date and time.

DateField: DateField is simply a serializer field that is used to represent the date.

TimeField: TimeField is simply a field of the serializer that is used to represent time.

DurationField: DurationField is simply a field of the serializer that is used to represent the duration.

ChoiceField: Choice Field is a type of CharField that is used for checking the input with the values that are out of limited choices set.

MultipleChoiceField: Choice Field is a type of CharField that is used for checking the input with the one, zero, or more values set and validating that the value is selected from the limited choices set.

FileField: FileField is a serializer field that represents a file. standard FileField validation of Django is performed by it.

ImageField: ImageField is a serializer field that represents an image. The content of the file uploaded is checked to validate that image has a known image format

ListField: ListField is a serializer field for checking the field input with the objects list.

JSONField: JSONField is simply a field class that is used to check whether the incoming data structure has proper JSON primitives or not.

HiddenField: HiddenField is simply a field class that takes its values from a callable value or default, instead of taking user input value.

DictField: DictField is a dictionary field that is used for checking the input with an object dictionary.

Core Arguments in Serializer Fields

Fields of Serializers Advance in Django are similar to both model fields of Django and Django form fields of Django and therefore for the fields manipulation, certain arguments are required by it.

read_only: This argument needs to be set as true to make sure that the field is used only for the process of serializing the representation. It should not be used in the process of updating and creating the instance during the serialization.

write_only: Arguments need to be set as true to make sure that the field must be used only at the time of instance creation and update process. It should not be used at the time of serializing the representation.

required: This argument is set as false so that there can be the omission of the object attributes or dictionary key from the output when the serialization of an instance takes place.

default: If we set the value to this argument, then it provides the default value and this will be used for the field having no input value.

allow_null: Generally, an error will occur if we pass 'none' in a field of the serializer. So, to overcome this error we set this argument as true. So that none will be represented as a valid input

validators: It is simply a list of various validator functions that must be used in the input of the incoming field and it can cause validation errors or return simply.

error_messages: It is an error code dictionary that simply displays error messages.

label: It is a small-size text string that can be used for naming any field in HTML form or for any other descriptive elements.

help_text: It is simply a text string that can be used for describing any field in HTML form or for any other descriptive elements.

initial: It is used for pre-populating the values present in the fields of HTML form.

Conclusion

  • Serializers enable the conversion of complex data like model instances and query sets into the native data types of Python.
  • Importing the serializer class of the rest_framework is required for basic serializer creation.
  • Shortcut is provided by the ModelSerializer class which enables automatic serializer class creation.
  • Hyperlinks are used by the HyperlinkedModelSerializer for relationships representation
  • BooleanField, EmailField, URLField, and RegexField are some of the fields of Serializers Advance in Django.
  • write_only, label, allow_null, and validators are some of the core arguments in the fields of the Serializers Advance in Django.