<p>Each field in a Form class is responsible not only for validating data, but also for "cleaning" it — normalizing it to a consistent format.</p>
<p>Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.</p>
<p><strong>Note:</strong> The serializer fields are declared in <code>fields.py</code>, but by convention you should import them using <code>from rest_framework import serializers</code> and refer to fields as <code>serializers.<FieldName></code>.</p>
<p>Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:</p>
<p>Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.</p>
<p>Set this to <code>True</code> to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.</p>
<p>Set this to <code>True</code> to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation.</p>
<p>Setting this to <code>False</code> also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.</p>
<p>If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.</p>
<p>The <code>default</code> is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.</p>
<p>May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a <code>set_context</code> method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for <ahref="../validators/#using-set_context">validators</a>.</p>
<p>Note that setting a <code>default</code> value implies that the field is not required. Including both the <code>default</code> and <code>required</code> keyword arguments is invalid and will raise an error.</p>
<p>Normally an error will be raised if <code>None</code> is passed to a serializer field. Set this keyword argument to <code>True</code> if <code>None</code> should be considered a valid value.</p>
<p>Note that, without an explicit <code>default</code>, setting this argument to <code>True</code> will imply a <code>default</code> value of <code>null</code> for serialization output, but does not imply a default for input deserialization.</p>
<p>The name of the attribute that will be used to populate the field. May be a method that only takes a <code>self</code> argument, such as <code>URLField(source='get_absolute_url')</code>, or may use dotted notation to traverse attributes, such as <code>EmailField(source='user.email')</code>. When serializing fields with dotted notation, it may be necessary to provide a <code>default</code> value if any object is not present or is empty during attribute traversal.</p>
<p>The value <code>source='*'</code> has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.</p>
<p>A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise <code>serializers.ValidationError</code>, but Django's built-in <code>ValidationError</code> is also supported for compatibility with validators defined in the Django codebase or third party Django packages.</p>
<p>When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to <code>False</code>, even if it has a <code>default=True</code> option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input.</p>
<p>Note that default <code>BooleanField</code> instances will be generated with a <code>required=False</code> option (since Django <code>models.BooleanField</code> is always <code>blank=True</code>). If you want to change this behaviour explicitly declare the <code>BooleanField</code> on the serializer class.</p>
<li><code>max_length</code> - Validates that the input contains no more than this number of characters.</li>
<li><code>min_length</code> - Validates that the input contains no fewer than this number of characters.</li>
<li><code>allow_blank</code> - If set to <code>True</code> then the empty string should be considered a valid value. If set to <code>False</code> then the empty string is considered invalid and will raise a validation error. Defaults to <code>False</code>.</li>
<p>The <code>allow_null</code> option is also available for string fields, although its usage is discouraged in favor of <code>allow_blank</code>. It is valid to set both <code>allow_blank=True</code> and <code>allow_null=True</code>, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.</p>
<p>A <code>RegexField</code> that validates the input against a URL matching pattern. Expects fully qualified URLs of the form <code>http://<host>/<path></code>.</p>
<p>Corresponds to <code>django.db.models.fields.URLField</code>. Uses Django's <code>django.core.validators.URLValidator</code> for validation.</p>
<p>A field that ensures the input is a valid UUID string. The <code>to_internal_value</code> method will return a <code>uuid.UUID</code> instance. On output the field will return a string in the canonical hyphenated format, for example:</p>
<li><code>path</code> - The absolute filesystem path to a directory from which this FilePathField should get its choice.</li>
<li><code>match</code> - A regular expression, as a string, that FilePathField will use to filter filenames.</li>
<li><code>recursive</code> - Specifies whether all subdirectories of path should be included. Default is <code>False</code>.</li>
<li><code>allow_files</code> - Specifies whether files in the specified location should be included. Default is <code>True</code>. Either this or <code>allow_folders</code> must be <code>True</code>.</li>
<li><code>allow_folders</code> - Specifies whether folders in the specified location should be included. Default is <code>False</code>. Either this or <code>allow_files</code> must be <code>True</code>.</li>
<li><code>protocol</code> Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.</li>
<li><code>unpack_ipv4</code> Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.</li>
<p>Corresponds to <code>django.db.models.fields.IntegerField</code>, <code>django.db.models.fields.SmallIntegerField</code>, <code>django.db.models.fields.PositiveIntegerField</code> and <code>django.db.models.fields.PositiveSmallIntegerField</code>.</p>
<li><code>max_digits</code> The maximum number of digits allowed in the number. It must be either <code>None</code> or an integer greater than or equal to <code>decimal_places</code>.</li>
<li><code>coerce_to_string</code> Set to <code>True</code> if string values should be returned for the representation, or <code>False</code> if <code>Decimal</code> objects should be returned. Defaults to the same value as the <code>COERCE_DECIMAL_TO_STRING</code> settings key, which will be <code>True</code> unless overridden. If <code>Decimal</code> objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting <code>localize</code> will force the value to <code>True</code>.</li>
<li><code>localize</code> Set to <code>True</code> to enable localization of input and output based on the current locale. This will also force <code>coerce_to_string</code> to <code>True</code>. Defaults to <code>False</code>. Note that data formatting is enabled if you have set <code>USE_L10N=True</code> in your settings file.</li>
<li><code>rounding</code> Sets the rounding mode used when quantising to the configured precision. Valid values are <ahref="https://docs.python.org/3/library/decimal.html#rounding-modes"><code>decimal</code> module rounding modes</a>. Defaults to <code>None</code>.</li>
<p>This field also takes an optional argument, <code>coerce_to_string</code>. If set to <code>True</code> the representation will be output as a string. If set to <code>False</code> the representation will be left as a <code>Decimal</code> instance and the final representation will be determined by the renderer.</p>
<p>If unset, this will default to the same value as the <code>COERCE_DECIMAL_TO_STRING</code> setting, which is <code>True</code> unless set otherwise.</p>
<li><code>format</code> - A string representing the output format. If not specified, this defaults to the same value as the <code>DATETIME_FORMAT</code> settings key, which will be <code>'iso-8601'</code> unless set. Setting to a format string indicates that <code>to_representation</code> return values should be coerced to string output. Format strings are described below. Setting this value to <code>None</code> indicates that Python <code>datetime</code> objects should be returned by <code>to_representation</code>. In this case the datetime encoding will be determined by the renderer.</li>
<li><code>input_formats</code> - A list of strings representing the input formats which may be used to parse the date. If not specified, the <code>DATETIME_INPUT_FORMATS</code> setting will be used, which defaults to <code>['iso-8601']</code>.</li>
<p>Format strings may either be <ahref="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior">Python strftime formats</a> which explicitly specify the format, or the special string <code>'iso-8601'</code>, which indicates that <ahref="https://www.w3.org/TR/NOTE-datetime">ISO 8601</a> style datetimes should be used. (eg <code>'2013-01-29T12:34:56.000000Z'</code>)</p>
<p>When a value of <code>None</code> is used for the format <code>datetime</code> objects will be returned by <code>to_representation</code> and the final output representation will determined by the renderer class.</p>
<h4id="auto_now-and-auto_now_add-model-fields"><aclass="toclink"href="#auto_now-and-auto_now_add-model-fields"><code>auto_now</code> and <code>auto_now_add</code> model fields.</a></h4>
<p>When using <code>ModelSerializer</code> or <code>HyperlinkedModelSerializer</code>, note that any model fields with <code>auto_now=True</code> or <code>auto_now_add=True</code> will use serializer fields that are <code>read_only=True</code> by default.</p>
<p>If you want to override this behavior, you'll need to declare the <code>DateTimeField</code> explicitly on the serializer. For example:</p>
<li><code>format</code> - A string representing the output format. If not specified, this defaults to the same value as the <code>DATE_FORMAT</code> settings key, which will be <code>'iso-8601'</code> unless set. Setting to a format string indicates that <code>to_representation</code> return values should be coerced to string output. Format strings are described below. Setting this value to <code>None</code> indicates that Python <code>date</code> objects should be returned by <code>to_representation</code>. In this case the date encoding will be determined by the renderer.</li>
<li><code>input_formats</code> - A list of strings representing the input formats which may be used to parse the date. If not specified, the <code>DATE_INPUT_FORMATS</code> setting will be used, which defaults to <code>['iso-8601']</code>.</li>
<p>Format strings may either be <ahref="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior">Python strftime formats</a> which explicitly specify the format, or the special string <code>'iso-8601'</code>, which indicates that <ahref="https://www.w3.org/TR/NOTE-datetime">ISO 8601</a> style dates should be used. (eg <code>'2013-01-29'</code>)</p>
<li><code>format</code> - A string representing the output format. If not specified, this defaults to the same value as the <code>TIME_FORMAT</code> settings key, which will be <code>'iso-8601'</code> unless set. Setting to a format string indicates that <code>to_representation</code> return values should be coerced to string output. Format strings are described below. Setting this value to <code>None</code> indicates that Python <code>time</code> objects should be returned by <code>to_representation</code>. In this case the time encoding will be determined by the renderer.</li>
<li><code>input_formats</code> - A list of strings representing the input formats which may be used to parse the date. If not specified, the <code>TIME_INPUT_FORMATS</code> setting will be used, which defaults to <code>['iso-8601']</code>.</li>
<p>Format strings may either be <ahref="https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior">Python strftime formats</a> which explicitly specify the format, or the special string <code>'iso-8601'</code>, which indicates that <ahref="https://www.w3.org/TR/NOTE-datetime">ISO 8601</a> style times should be used. (eg <code>'12:34:56.000000'</code>)</p>
<p>A field that can accept a value out of a limited set of choices.</p>
<p>Used by <code>ModelSerializer</code> to automatically generate fields if the corresponding model field includes a <code>choices=…</code> argument.</p>
<li><code>allow_blank</code> - If set to <code>True</code> then the empty string should be considered a valid value. If set to <code>False</code> then the empty string is considered invalid and will raise a validation error. Defaults to <code>False</code>.</li>
<li><code>html_cutoff</code> - 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 <code>None</code>.</li>
<li><code>html_cutoff_text</code> - 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 <code>"More than {count} items…"</code></li>
<p>Both the <code>allow_blank</code> and <code>allow_null</code> are valid options on <code>ChoiceField</code>, although it is highly recommended that you only use one and not both. <code>allow_blank</code> should be preferred for textual choices, and <code>allow_null</code> should be preferred for numeric or other non-textual choices.</p>
<p>A field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. <code>to_internal_value</code> returns a <code>set</code> containing the selected values.</p>
<li><code>allow_blank</code> - If set to <code>True</code> then the empty string should be considered a valid value. If set to <code>False</code> then the empty string is considered invalid and will raise a validation error. Defaults to <code>False</code>.</li>
<li><code>html_cutoff</code> - 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 <code>None</code>.</li>
<li><code>html_cutoff_text</code> - 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 <code>"More than {count} items…"</code></li>
<p>As with <code>ChoiceField</code>, both the <code>allow_blank</code> and <code>allow_null</code> options are valid, although it is highly recommended that you only use one and not both. <code>allow_blank</code> should be preferred for textual choices, and <code>allow_null</code> should be preferred for numeric or other non-textual choices.</p>
<p>The <code>FileField</code> and <code>ImageField</code> classes are only suitable for use with <code>MultiPartParser</code> or <code>FileUploadParser</code>. Most parsers, such as e.g. JSON don't support file uploads.
Django's regular <ahref="https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS">FILE_UPLOAD_HANDLERS</a> are used for handling uploaded files.</p>
<li><code>max_length</code> - Designates the maximum length for the file name.</li>
<li><code>allow_empty_file</code> - Designates if empty files are allowed.</li>
<li><code>use_url</code> - If set to <code>True</code> then URL string values will be used for the output representation. If set to <code>False</code> then filename string values will be used for the output representation. Defaults to the value of the <code>UPLOADED_FILES_USE_URL</code> settings key, which is <code>True</code> unless set otherwise.</li>
<li><code>max_length</code> - Designates the maximum length for the file name.</li>
<li><code>allow_empty_file</code> - Designates if empty files are allowed.</li>
<li><code>use_url</code> - If set to <code>True</code> then URL string values will be used for the output representation. If set to <code>False</code> then filename string values will be used for the output representation. Defaults to the value of the <code>UPLOADED_FILES_USE_URL</code> settings key, which is <code>True</code> unless set otherwise.</li>
<p>Requires either the <code>Pillow</code> package or <code>PIL</code> package. The <code>Pillow</code> package is recommended, as <code>PIL</code> is no longer actively maintained.</p>
<li><code>child</code> - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.</li>
<p>We can now reuse our custom <code>StringListField</code> class throughout our application, without having to provide a <code>child</code> argument to it.</p>
<li><code>child</code> - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.</li>
</ul>
<p>For example, to create a field that validates a mapping of strings to strings, you would write something like this:</p>
<li><code>child</code> - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.</li>
</ul>
<p>Note that the child field <strong>must</strong> be an instance of <code>CharField</code>, as the hstore extension stores values as strings.</p>
<p>A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings.</p>
<li><code>binary</code> - If set to <code>True</code> then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to <code>False</code>.</li>
<p>A field class that simply returns the value of the field without modification.</p>
<p>This field is used by default with <code>ModelSerializer</code> when including field names that relate to an attribute rather than a model field.</p>
<p>For example, if <code>has_expired</code> was a property on the <code>Account</code> model, then the following serializer would automatically generate it as a <code>ReadOnlyField</code>:</p>
<p>The <code>HiddenField</code> class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user.</p>
<p>A generic field that can be tied to any arbitrary model field. The <code>ModelField</code> class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.</p>
<p>This field is used by <code>ModelSerializer</code> to correspond to custom model field classes.</p>
<p>The <code>ModelField</code> class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a <code>ModelField</code>, it must be passed a field that is attached to an instantiated model. For example: <code>ModelField(model_field=MyModel()._meta.get_field('custom_field'))</code></p>
<p>This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.</p>
<li><code>method_name</code> - The name of the method on the serializer to be called. If not included this defaults to <code>get_<field_name></code>.</li>
<p>The serializer method referred to by the <code>method_name</code> argument should accept a single argument (in addition to <code>self</code>), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:</p>
<pre><code>from django.contrib.auth.models import User
from django.utils.timezone import now
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
<p>If you want to create a custom field, you'll need to subclass <code>Field</code> and then override either one or both of the <code>.to_representation()</code> and <code>.to_internal_value()</code> methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, <code>date</code>/<code>time</code>/<code>datetime</code> or <code>None</code>. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using.</p>
<p>The <code>.to_representation()</code> method is called to convert the initial datatype into a primitive, serializable datatype.</p>
<p>The <code>to_internal_value()</code> method is called to restore a primitive datatype into its internal python representation. This method should raise a <code>serializers.ValidationError</code> if the data is invalid.</p>
<p>Note that the <code>WritableField</code> class that was present in version 2.x no longer exists. You should subclass <code>Field</code> and override <code>to_internal_value()</code> if the field supports data input.</p>
<p>By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override <code>.get_attribute()</code> and/or <code>.get_value()</code>.</p>
red, green, blue = [int(col) for col in data.split(',')]
if any([col > 255 or col < 0 for col in (red, green, blue)]):
raise ValidationError('Value out of range. Must be between 0 and 255.')
return Color(red, green, blue)
</code></pre>
<p>The <code>.fail()</code> method is a shortcut for raising <code>ValidationError</code> that takes a message string from the <code>error_messages</code> dictionary. For example:</p>
<pre><code>default_error_messages = {
'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',
<p>Here we'll take an example of a <em>flat</em><code>DataPoint</code> model with <code>x_coordinate</code> and <code>y_coordinate</code> attributes.</p>
<pre><code>class DataPoint(models.Model):
label = models.CharField(max_length=50)
x_coordinate = models.SmallIntegerField()
y_coordinate = models.SmallIntegerField()
</code></pre>
<p>Using a custom field and <code>source='*'</code> we can provide a nested representation of
<p>The <ahref="https://drf-compound-fields.readthedocs.io">drf-compound-fields</a> package provides "compound" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the <code>many=True</code> option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type.</p>
<p>The <ahref="https://github.com/Hipo/drf-extra-fields">drf-extra-fields</a> package provides extra serializer fields for REST framework, including <code>Base64ImageField</code> and <code>PointField</code> classes.</p>
<p>the <ahref="https://github.com/heywbj/django-rest-framework-recursive">djangorestframework-recursive</a> package provides a <code>RecursiveField</code> for serializing and deserializing recursive structures</p>
<p>The <ahref="https://github.com/djangonauts/django-rest-framework-gis">django-rest-framework-gis</a> package provides geographic addons for django rest framework like a <code>GeometryField</code> field and a GeoJSON serializer.</p>
<p>The <ahref="https://github.com/djangonauts/django-rest-framework-hstore">django-rest-framework-hstore</a> package provides an <code>HStoreField</code> to support <ahref="https://github.com/djangonauts/django-hstore">django-hstore</a><code>DictionaryField</code> model field.</p>