Monday, November 18, 2024
Google search engine
HomeLanguagesSerializer Fields – Django REST Framework

Serializer Fields – Django REST Framework

Serializer comes with some fields (entries) that process data in and out of the serializer in Django REST Framework. The very motive of Serializing is to convert DB data to a datatype that can be used by javascript. For example, if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField, CharField and BooleanField for storing and manipulating data through Django. One needs multiple fields for imparting default validations to data, i.e., one would use EmailField for storing email because it validates the data to an email address. 
This article revolves around multiple fields one can use in a serializer in Django REST Framework and how one can use them. Serializer Fields in Django REST Framework can be divided into following categories – 

Boolean Fields

There are two major fields for Boolean Fields – BooleanField and NullBooleanField.  

BooleanField

A boolean field used to wrap True or False values. It works the same as BooleanField – Django Models. By default, serializers.BooleanField instances as created by default as False. 
Syntax – 

field_name = serializers.BooleanField() 

NullBooleanField

A boolean field that accepts True, False and Null values. It works the same as NullBooleanField – Django Models. By default, serializers.NullBooleanField instances as created by default as none. 
Syntax –  

field_name = serializers.NullBooleanField()

To check more, visit – Boolean Fields in Serializers – Django REST Framework  

String Fields

There are three major fields – CharField, EmailField and RegexField.  

CharField

CharField is used to store text representation. Optionally validates the text to be shorter than max_length and longer than min_length. It works the same as CharField – Django Models
It has the following arguments –  

  • max_length – Validates that the input contains no more than this number of characters.
  • min_length – Validates that the input contains no fewer than this number of characters.
  • allow_blank – If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False.
  • trim_whitespace – If set to True then leading and trailing whitespace is trimmed. Defaults to True.

Syntax – 

field_name = serializers.CharField(*args, **kwargs) 

EmailField

EmailField is also a text representation and it validates the text to be a valid e-mail address. It is same as EmailField – Django Models. It takes all of the arguments of CharField for same functionalities. 
Syntax – 

field_name = serializers.EmailField(*args, **kwargs) 

RegexField

As the name defines, RegexField matches the string to a particular regex, else raises an error. It is same as RegexField – Django Forms. It takes all of the arguments of CharField for same functionalities. 
Syntax –  

field_name = serializers.RegexField(*args, **kwargs)

To check more, visit – String Fields in Serializers – Django REST Framework  

URL Fields

There are two major fields – URLField and SlugField.  

URLField

URLField is basically a RegexField that validates the input against a URL matching pattern. Expects fully qualified URLs of the form http:///. It works the same as URLField – Django Models 

It has the following arguments –  

  • allow_blank – If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False.

Syntax – 

field_name = serializers.URLField(*args, **kwargs) 

SlugField

SlugField is a RegexField that validates the input against the pattern [a-zA-Z0-9_-]+. It is same as SlugField – Django Models

Syntax –  

field_name = serializers.SlugField(*args, **kwargs)

To check more, visit – URL fields in serializers – Django REST Framework  

Numeric Fields

There are three major fields – IntegerField, FloatField and DecimalField.  

IntegerField

IntegerField is basically a integer field that validates the input against Python’s int instance.It is same as IntegerField – Django Models 

It has the following arguments –  

  • max_value Validate that the number provided is no greater than this value.
  • min_value Validate that the number provided is no less than this value.

Syntax – 

field_name = serializers.IntegerField(*args, **kwargs) 

FloatField

FloatField is basically a float field that validates the input against Python’s float instance.It is same as FloatField – Django Models 

It has the following arguments –  

  • max_value Validate that the number provided is no greater than this value.
  • min_value Validate that the number provided is no less than this value.

Syntax – 

field_name = serializers.FloatField(*args, **kwargs) 

DecimalField

DecimalField is basically a decimal field that validates the input against Python’s decimal instance.It is same as DecimalField – Django Models 

It has the following arguments –  

  • max_digits The maximum number of digits allowed in the number. It must be either None or an integer greater than or equal to decimal_places.
  • decimal_places The number of decimal places to store with the number.
  • max_value Validate that the number provided is no greater than this value.
  • min_value Validate that the number provided is no less than this value.
  • localize Set to True to enable localization of input and output based on the current locale.

Syntax –  

field_name = serializers.DecimalField(*args, **kwargs)

To check more, visit – Numeric fields in serializers – Django REST Framework  

Date and Time Fields

There are four major fields – DateTimeField, DateField, TimeField and DurationField. 
 

DateTimeField

DateTimeField is a serializer field used for date and time representation. It is same as – DateTimeField – Django Models 

It has the following arguments –  

  • format – A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be ‘iso-8601’ unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python datetime objects should be returned by to_representation. In this case the datetime encoding will be determined by the renderer.
  • input_formats – A list of strings representing the input formats which may be used to parse the date. If not specified, the DATETIME_INPUT_FORMATS setting will be used, which defaults to [‘iso-8601’].
  • default_timezone – A pytz.timezone representing the timezone. If not specified and the USE_TZ setting is enabled, this defaults to the current timezone. If USE_TZ is disabled, then datetime objects will be naive.

Syntax – 

field_name = serializers.DateTimeField(*args, **kwargs) 

DateField

DateField is a serializer field used for date representation. Often, one needs to store date such as in a blog model every post’s date needs to be stored. This field is same as DateField – Django Models 
It has the following arguments –  

  • format – A string representing the output format. If not specified, this defaults to the same value as the DATE_FORMAT settings key, which will be ‘iso-8601’ unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python date objects should be returned by to_representation. In this case the date encoding will be determined by the renderer.
  • input_formats – A list of strings representing the input formats which may be used to parse the date. If not specified, the DATE_INPUT_FORMATS setting will be used, which defaults to [‘iso-8601’].

Syntax – 

field_name = serializers.DateField(*args, **kwargs) 

TimeField

Timefield is a serializer field used for time representation. Often, one needs to store date such as in a blog model every post’s time needs to be stored. 

It has the following arguments –  

  • format – A string representing the output format. If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be ‘iso-8601’ unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python time objects should be returned by to_representation. In this case the time encoding will be determined by the renderer.
  • input_formats – A list of strings representing the input formats which may be used to parse the date. If not specified, the TIME_INPUT_FORMATS setting will be used, which defaults to [‘iso-8601’].

Syntax – 

field_name = serializers.TimeField(*args, **kwargs) 

DurationField

DurationField is a serializer field used for duration representation. This field is same as DurationField – Django Models 
It has the following arguments –  

  • max_value Validate that the duration provided is no greater than this value.
  • min_value Validate that the duration provided is no less than this value.

Syntax –  

field_name = serializers.DurationField(*args, **kwargs)

To check more, visit – Date and time fields in serializers – Django REST Framework  

Choice Selection Fields

There are two major fields – Choice and MultipleChioceField. 
 

ChoiceField

ChoiceField is basically a CharField that validates the input against a value out of a limited set of choices. This field is same as ChoiceField – Django Forms

It has the following arguments –  

  • choices – A list of valid values, or a list of (key, display_name) tuples.
  • allow_blank – If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False.
  • html_cutoff – If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to None.
  • html_cutoff_text – If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to “More than {count} items…”

Syntax – 

field_name = serializers.ChoiceField(*args, **kwargs) 

MultipleChoiceField

ChoiceField is basically a CharField that validates the input against a set of zero, one or many values, chosen from a limited set of choices. This field is same as MultipleChoiceField – Django Forms

Syntax –  

field_name = serializers.MultipleChoiceField(*args, **kwargs)

To check more, visit – Choice Selection Fields in serializers – Django REST Framework  

File Upload Fields

There are two major fields – FileField and ImageField.  

FileField

FileField is basically a file representation. It performs Django’s standard FileField validation. This field is same as FileField – Django Models

It has the following arguments –  

  • max_length – Designates the maximum length for the file name.
  • allow_empty_file – Designates if empty files are allowed.
  • use_url – If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise.

Syntax – 

field_name = serializers.FileField(*args, **kwargs) 

ImageField

ImageField is an image representation.It validates the uploaded file content as matching a known image format. This is same as ImageField – Django forms 

It has the following arguments –  

  • max_length – Designates the maximum length for the file name.
  • allow_empty_file – Designates if empty files are allowed.
  • use_url – If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise.

Syntax –  

field_name = serializers.ImageField(*args, **kwargs)

To check more, visit – File upload Fields in Serializers – Django REST Framework 

Serializer Fields

.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; }  

Field Name Description
BooleanField A boolean field used to wrap True or False values.
NullBooleanField A boolean field that accepts True, False and Null values.
CharField CharField is used to store text representation.
EmailField EmailField is also a text representation and it validates the text to be a valid e-mail address.
RegexField As the name defines, RegexField matches the string to a particular regex, else raises an error.
URLField URLField is basically a RegexField that validates the input against a URL matching pattern.
SlugField SlugField is a RegexField that validates the input against the pattern [a-zA-Z0-9_-]+.
IPAddressField IPAddressField is a field that ensures the input is a valid IPv4 or IPv6 string.
IntegerField IntegerField is basically a integer field that validates the input against Python’s int instance.
FloatField FloatField is basically a float field that validates the input against Python’s float instance.
DecimalField DecimalField is basically a decimal field that validates the input against Python’s decimal instance.
DateTimeField DateTimeField is a serializer field used for date and time representation.
DateField DateField is a serializer field used for date representation.
TimeField Timefield is a serializer field used for time representation.
DurationField DurationField is a serializer field used for duration representation.
ChoiceField ChoiceField is basically a CharField that validates the input against a value out of a limited set of choices.
MultipleChoiceField MultipleChoiceField is basically a CharField that validates the input against a set of zero, one or many values, chosen from a limited set of choices.
FileField FileField is basically a file representation. It performs Django’s standard FileField validation.
ImageField ImageField is an image representation.It validates the uploaded file content as matching a known image format.
ListField ListField is basically a list field that validates the input against a list of objects.
JSONField JSONField is basically a field class that validates that the incoming data structure consists of valid JSON primitives.
HiddenField HiddenField is a field class that does not take a value based on user input, but instead takes its value from a default value or callable.
DictField DictField is basically a dictionary field that validates the input against a dictionary of objects.

Core arguments in serializer fields

Serializer fields in Django are same as Django Form fields and Django model fields and thus require certain arguments to manipulate the behaviour of those Fields. 

.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; }  

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.
source The name of the attribute that will be used to populate the field.
validators A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return.
error_messages A dictionary of error codes to error messages.
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 that should be used for pre-populating the value of HTML form fields.
RELATED ARTICLES

Most Popular

Recent Comments