Serializer Fields - Django REST Framework - GeeksforGeeks

26 Sep, 2021
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
String Fields
Numeric Fields
Date and Time Fields
Choice Selection Fields
File Upload Fields
Serializer Fields
Core arguments in serializer fields 
There are two major fields for Boolean Fields – BooleanField and NullBooleanField.  
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() 
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  
There are three major fields – CharField, EmailField and RegexField.  
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 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) 
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  
There are two major fields – URLField and SlugField.  
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 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  
There are three major fields – IntegerField, FloatField and DecimalField.  
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 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 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  
There are four major fields – DateTimeField, DateField, TimeField and DurationField.  
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 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 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 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  
There are two major fields – Choice and MultipleChioceField.  
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) 
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  
There are two major fields – FileField and ImageField.  
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 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 
.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; }  
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; }  
ruhelaa48
Django-REST
Python Django
rest-framework
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()