<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>
<hr/>
<p><strong>Note:</strong> The serializer fields are declared in fields.py, 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>
<hr/>
<h2id="core-arguments">Core arguments</h2>
<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>
<h3id="source"><code>source</code></h3>
<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>Field(source='get_absolute_url')</code>, or may use dotted notation to traverse attributes, such as <code>Field(source='user.email')</code>.</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. (See the implementation of the <code>PaginationSerializer</code> class for an example.)</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>Defaults to <code>False</code></p>
<h3id="write_only"><code>write_only</code></h3>
<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>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 behavior is to not populate the attribute at all. </p>
class AccountSerializer(serializers.HyperlinkedModelSerializer):
expired = serializers.Field(source='has_expired')
class Meta:
fields = ('url', 'owner', 'name', 'expired')
</code></pre>
<p>Would produce output similar to:</p>
<preclass="prettyprint lang-py"><code>{
'url': 'http://example.com/api/accounts/3/',
'owner': 'http://example.com/api/users/12/',
'name': 'FooCorp business account',
'expired': True
}
</code></pre>
<p>By default, the <code>Field</code> class will perform a basic translation of the source value into primitive datatypes, falling back to unicode representations of complex datatypes when necessary.</p>
<p>You can customize this behavior by overriding the <code>.to_native(self, value)</code> method.</p>
<h2id="writablefield">WritableField</h2>
<p>A field that supports both read and write operations. By itself <code>WritableField</code> does not perform any translation of input values into a given type. You won't typically use this field directly, but you may want to override it and implement the <code>.to_native(self, value)</code> and <code>.from_native(self, value)</code> methods.</p>
<h2id="modelfield">ModelField</h2>
<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 it's 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>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. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method 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>
<preclass="prettyprint lang-py"><code>from django.contrib.auth.models import User
from django.utils.timezone import now
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
<p>Corresponds to <code>django.db.models.fields.DateTimeField</code></p>
<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>
<p>Note that by default, datetime representations are determined by the renderer in use, although this can be explicitly overridden as detailed below.</p>
<p>In the case of JSON this means the default datetime representation uses the <ahref="http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15">ECMA 262 date time string specification</a>. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: <code>2013-01-29T12:34:56.123Z</code>.</p>
<li><code>format</code> - A string representing the output format. If not specified, this defaults to <code>None</code>, which indicates that Python <code>datetime</code> objects should be returned by <code>to_native</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>
</ul>
<p>DateTime format strings may either be <ahref="http://docs.python.org/2/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="http://www.w3.org/TR/NOTE-datetime">ISO 8601</a> style datetimes should be used. (eg <code>'2013-01-29T12:34:56.000000Z'</code>)</p>
<h2id="datefield">DateField</h2>
<p>A date representation.</p>
<p>Corresponds to <code>django.db.models.fields.DateField</code></p>
<li><code>format</code> - A string representing the output format. If not specified, this defaults to <code>None</code>, which indicates that Python <code>date</code> objects should be returned by <code>to_native</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>
</ul>
<p>Date format strings may either be <ahref="http://docs.python.org/2/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="http://www.w3.org/TR/NOTE-datetime">ISO 8601</a> style dates should be used. (eg <code>'2013-01-29'</code>)</p>
<h2id="timefield">TimeField</h2>
<p>A time representation.</p>
<p>Optionally takes <code>format</code> as parameter to replace the matching pattern.</p>
<p>Corresponds to <code>django.db.models.fields.TimeField</code></p>
<li><code>format</code> - A string representing the output format. If not specified, this defaults to <code>None</code>, which indicates that Python <code>time</code> objects should be returned by <code>to_native</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>
</ul>
<p>Time format strings may either be <ahref="http://docs.python.org/2/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="http://www.w3.org/TR/NOTE-datetime">ISO 8601</a> style times should be used. (eg <code>'12:34:56.000000'</code>)</p>
<h2id="integerfield">IntegerField</h2>
<p>An integer representation.</p>
<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>
<h2id="floatfield">FloatField</h2>
<p>A floating point representation.</p>
<p>Corresponds to <code>django.db.models.fields.FloatField</code>.</p>
<h2id="decimalfield">DecimalField</h2>
<p>A decimal representation.</p>
<p>Corresponds to <code>django.db.models.fields.DecimalField</code>.</p>
<h2id="filefield">FileField</h2>
<p>A file representation. Performs Django's standard FileField validation.</p>
<p>Corresponds to <code>django.forms.fields.FileField</code>.</p>
<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>
<p>Signature and validation is the same as with <code>FileField</code>.</p>
<hr/>
<p><strong>Note:</strong><code>FileFields</code> and <code>ImageFields</code> are only suitable for use with MultiPartParser, since e.g. json doesn't support file uploads.
Django's regular <ahref="https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS">FILE_UPLOAD_HANDLERS</a> are used for handling uploaded files.</p>
<hr/>
<h1id="custom-fields">Custom fields</h1>
<p>If you want to create a custom field, you'll probably want to override either one or both of the <code>.to_native()</code> and <code>.from_native()</code> methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes may be any of a number, string, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primitive objects.</p>
<p>The <code>.to_native()</code> method is called to convert the initial datatype into a primitive, serializable datatype. The <code>from_native()</code> method is called to restore a primitive datatype into it's initial representation.</p>
<h2id="examples">Examples</h2>
<p>Let's look at an example of serializing a class that represents an RGB color value:</p>
red, green, blue = [int(col) for col in data.split(',')]
return Color(red, green, blue)
</code></pre>
<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>.field_to_native()</code> and/or <code>.field_from_native()</code>.</p>
<p>As an example, let's create a field that can be used represent the class name of the object being serialized:</p>