Serializers in Django
Overview
The Django REST Framework's serializers are in charge of transforming objects into data formats that front-end frameworks and javascript can understand. In this tutorial, we'll learn about serializers, their features, configuration, and usage. Let's get started.
Pre-requisites
- Python programming language
- Django structure
- Brief about DRF(Django Rest Framework)
Introduction to Serializers in Django
Data is transformed by serialization into a format that is suitable for transmission or storing, after which it is reconstructed. The most well-known serializer is serializers in Django or serializers in Django Rest Framework (Django Rest Framework). Objects in the Django REST Framework must be serialized into data types that front-end frameworks and javascript can comprehend. Following the initial validation of the incoming data, serializers also offer deserialization, enabling the conversion of parsed data back into complicated types. The REST framework's serializers operate quite similarly to Django's Form and ModelForm classes. The two main serializers that are used the most frequently are ModelSerializer and HyperLinkedModelSerialzer.
Through the use of serializers, complicated data, such as querysets and model instances, can be transformed into JSON, XML, or other content kinds with ease using native Python datatypes. Following the initial validation of the incoming data, serializers also offer deserialization, enabling the conversion of parsed data back into complicated types.
Declaring Serializers
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. Declaring serializers in Django:
Just like when building a form or model in Django, the first step in establishing a basic serializer is to import the serializers class from the rest framework and define the serializer's fields.
The fields that are serialized and deserialized are defined by the serializer class.
Using Serializer to Serialize Data
To serialize a record or list of records, we may now use RecordSerializer. Once more, utilizing a Form class appears to be very similar to using the Serializer class.
ModelSerializer
ModelSerializer is an abstraction layer over Django's default serializer that enables the easy creation of a serializer for a model. A wrapper for the standard Django Framework, the Django REST Framework is primarily used to develop different types of APIs.
A ModelSerializer, similar to a ModelForm, offers an API for building serializers from your models. The Form and ModelForm classes in Django function quite similarly to the serializers in the REST framework. It offers a ModelSerializer class that acts as a convenient shortcut for developing serializers that deal with model instances and querysets, as well as a Serializer class that allows you a strong, general approach to managing the output of your responses.
With the help of the ModelSerializer class, you can quickly generate a Serializer class in django with fields that match the Model fields. Similar to a standard Serializer class, the ModelSerializer class has the following differences:
- Based on the model, it will create a set of fields for you automatically.
- Validators like unique together validators will be generated automatically for the serializer.
- It features straightforward.create()and.update defaultimplementations ()`.
Syntax for ModelSerialzer:
Example:
Just like when building a form or model in Django, the first step in establishing a basic serializer is to import the serializers class from the rest framework and define the serializer's fields.
Declaring a serializer:
Specifying Which Fields Should be Included
Similar to how you would with a ModelForm, you may utilize fields or exclude options to limit the default fields that are used in a model serializer. Example:
or exclude Example:
Specifying Nested Serialization
It is possible to incorporate the referred entity via layered relationships. Primary keys are used for relationships by default in the ModelSerializer, but you can also quickly create nested representations by using the depth option:
The depth option needs to be set to an integer value that represents the number of relationships that need to be traversed in depth before returning to a flat representation.
Specifying which Fields Should be Read-Only
It could be a good idea to mark many fields as read-only. You can use the read_only_fields Meta option instead of explicitly adding the read only=True attribute to each field
Example:
It is not necessary to add read-only fields to the read-only fields option for model fields with editable=False set or for AutoField fields because they are read-only by default.
Specifying Which Fields Should be Write-Only
It may be desirable to designate numerous fields as write-only. You can use the write_only_fields Meta option instead of explicitly adding the write only=True attribute to each field
Example:
Relational Fields
There are numerous alternatives for representing relationships when serializing model instances. The primary keys of the associated instances are used as the model serializer's default representation.
Example:
Using its __unicode__ method, RelatedField can be utilized to express the relationship's target.
Would serialize to the following representation
HyperlinkedModelSerializer
The HyperlinkedModelSerializer is an abstraction layer over the Django default serializer that makes it easy to quickly develop a serializer for a model in django. The HyperlinkedModelSerializer in the Django REST Framework serializers is the focus of this section. In contrast to the ModelSerializer class, the HyperlinkedModelSerializer class represents relationships using hyperlinks rather than primary keys. Instead of a main key field by default, the serializer will contain a url field. Any relationships on the model will be represented by a HyperlinkedRelatedField serializer field, and the url field will be represented by a HyperlinkedIdentityField serializer field.
syntax:
Instead of a main key field by default, the serializer will contain a url field.
By adding the primary key to the fields option, you can specifically include it.
For example:
How Hyperlinked Views are Determined?
It must be possible to choose which views to link to model instances. By default, hyperlinks should point to a view name that matches the style " model name-detail" and seeks up the instance using the pk keyword parameter.
By adjusting the lookup_field option, you can modify the field that is used for object lookups. This option's value should match a field on the model as well as a kwarg in the URL configuration.
Example:
All hyperlinked fields—including the URL identity and any hyperlinked relationships—will use the lookup_field by default. You should explicitly set the fields on the serializer for more specific requirements, such as setting a different lookup for each field.
Overriding the URL Field Behavior
The URL field's name is always set to "url". Using the URL FIELD NAME setting, you can globally override this. Using the serializer's url field name option, you may easily customize this for each serializer.
Example:
The view name and lookup field options allow you to modify the URL field's view name and lookup field without changing the field itself:
Serializer Fields
In REST Framework, the Django seDjangoer has a few fields (entries) that handle data entering and exiting the serializer. The fundamental purpose of serializing is to transform database data into a datatype that javascript can use. As an example, suppose you have a class called Records with the attributes record_id, name, etc. You would then require AutoField, CharField, and BooleanField for Django to store and manipulate data. For data to receive default validations, one requires numerous fields. The categories of serializer fields in the Django REST Framework are as follows:
- Boolean Fields: A field that stores True or False values in boolean format. It functions in a similar way to BooleanField - Django Models. Serializers by default.
Syntax:
- String Fields: CharField, EmailField, and RegexField are the three main fields.
-
CharField: To store text representation, use CharField. Optionally checks that the text is longer than the min length and shorter than the max length. It functions similarly to CharField - Django Models. It has the following reasons:
- max_length: Verifies that the input includes no more characters than the value specified by max length.
- min_length: Verifies that the input contains at least this many characters, but not fewer.
- allow_blank: If set to True, the empty string ought to be regarded as a valid value. The empty string is regarded as invalid and will cause a validation error if set to False.
- trim_whitespace
and following whitespace are trimmed if trim whitespace is set to True.
Syntax:
-
EmailField: Additionally a text representation, EmailField verifies the content to be an actual email address. The EmailField - Django Models equivalent is used. It also has all the parameters of CharField for the same functionalities.
Syntax:
-
RegexField: RegexField, as its name suggests, matches the string to a specific regex, failing which it raises an error. The RegexField - Django Forms equivalent. For the same functionality, it accepts all of CharField's parameters.
Syntax:
-
- Numeric Fields:
IntegerField, FloatField, and DecimalField are the three main fields.
-
IntegerField: IntegerField is a field that checks input against Python's int instance. It has the following justifications:
- max_value: Verify that the specified number does not exceed this value.
- min_value: Verify that the specified number does not fall below this amount.
Syntax:
-
FloatField: In essence, FloatField is a float field that verifies input against the Python float instance.
Syntax:
-
DecimalField: In essence, DecimalField is a decimal field that verifies input against the Python decimal instance. It has the following justifications:
- max_digits: The most digits that can be included in the number. Either None or an integer bigger than or equal to decimal places must be used.
- decimal_places: It tells how many decimal places should be stored beside the number.
- max_value: Verify that the specified number does not exceed this value.
- min_value: Verify that the specified number does not fall below this amount.
- localize: If True is selected, input and output will be localized according to the current locale.
Syntax:
-
- Date and Time Fields:
DateTimeField, DateField, TimeField, and DurationField are the four main fields.
-
DateTimeField: A serializer field called DateTimeField is used to express dates and times.
Syntax:
-
DateField: A serializer field called DateField is used to represent dates. It is frequently necessary to keep dates, for example, the date of each post in a blog model.
Syntax:
-
TimeField*: A serializer field called the Time field is used to express time. It is frequently necessary to keep dates, for example, the time of each post in a blog model.
Syntax:
-
DurationField: A serializer field called DurationField is used to indicate durations.
Syntax:
-
- Choice Selection Fields:
-
ChoiceField: A ChoiceField is essentially a CharField that compares the input to a value from a constrained list of options.
Syntax:
-
MultipleChoiceField: In essence, a ChoiceField is a CharField that compares the input to a set of zero, one, or many values that are selected from a constrained list of options.
Syntax:
-
- File Upload Fields:
-
FileField: Essentially, FileField is a file representation. It carries out the usual FileField validation tasks in Django.
Syntax:
-
*ImageField *: An image representation is called ImageField. It confirms that the uploaded file's content adheres to a recognized image format.
Syntax:
-
Core Arguments in Serializer Fields:
The behavior of Django's serializer fields can be changed using specific parameters just like that of the model fields and form fields.
Parameters | Description |
---|---|
read_only | If you want to make sure the field is used when serializing a representation but not when creating or modifying an instance during deserialization, set this to True. |
write_only | If you want the field to be used when creating or modifying an instance but not when serializing the representation, set this to True. |
required | When serializing the instance, the object attribute or dictionary key may also be left out if this is set to False. |
default | Whenever this value is set, the default value—which will be used if no input value is provided—for the field is displayed. |
validators | A list of validator functions that should be used on the receiving field input and then eitherraisese a validation error or just return. |
label | A brief text string that can be used in HTML form fields or other descriptor elements to identify a field. |
help_text | A textual description that can be used in HTML form fields or other describe components. |
Advanced Serializer Usage
ModelSerializer or HyperlinkedModelSerializer can have customized subclasses that use a different set of default fields. This type of advanced usage is only required if you have certain serializers in Djangoneeds to be repeated.
Dynamically Modifying Fields
Once a serializer has been initialized, the.fields attribute can be used to retrieve the dictionary of fields that have been set on the serializer. You can dynamically alter the serializer by gaining access to and changing this attribute.
When you directly alter the fields argument, you may do interesting things like alter the arguments on the serializer fields at runtime rather than when you first declare the serializer.
Example
For instance, you could define a serializer class in the following way if you wanted to be able to specify which fields a serializer should utilize when it is initialized:
This would then allow you to do the following:
Customizing the Default Fields
Model classes and serializer classes in django are mapped in a dictionary via the field_mapping attribute. A different set of default serializer classes can be set by overriding the attribute. You can override other get_<field_type>_field methods for more intricate customization than simply altering the default serializer class. By doing this, you can alter the arguments used to initialize each serializer field. These methods each have a possible return value of a field, a serializer object, or None.
- get_pk_field: Returns the relevant field instance to be utilized when depth is defined as being non-zero.
- get_related_field: Returns the field instance that must be used to represent a related field in the absence of a depth specification or when nested representations are being utilized and the depth reaches zero.
- get_field: Returns the non-relational, non-pk field object to be used.
Example
Conclusion
In the above article, we learn about
- DRF's serializers or serializers in django that are in charge of transforming objects into data formats.
- We go through how to declare Serializers, and various Serializer Fields like read_only, write_only, required, default, etc.
- As you can see, having custom serializer fields drastically streamlines your serializer code and encapsulates the field logic so that it can be utilized throughout your application without code repetition.