<p>Expanding the usefulness of the serializers is something that we would
like to address. However, it's not a trivial problem, and it
will take some serious design work. Any offers to help out in this
area would be gratefully accepted.</p>
<p>— Russell Keith-Magee, <ahref="https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion">Django users group</a></p>
</blockquote>
<p>Serializers allow complex data such as querysets and model instances to be converted to native python datatypes that can then be easily rendered into <code>JSON</code>, <code>XML</code> or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.</p>
<p>REST framework's serializers work very similarly to Django's <code>Form</code> and <code>ModelForm</code> classes. It provides a <code>Serializer</code> class which gives you a powerful, generic way to control the output of your responses, as well as a <code>ModelSerializer</code> class which provides a useful shortcut for creating serializers that deal with model instances and querysets.</p>
<p>The first part of serializer class defines the fields that get serialized/deserialized. The <code>restore_object</code> method defines how fully fledged instances get created when deserializing data. The <code>restore_object</code> method is optional, and is only required if we want our serializer to support deserialization.</p>
<p>We can now use <code>CommentSerializer</code> to serialize a comment, or list of comments. Again, using the <code>Serializer</code> class looks a lot like using a <code>Form</code> class.</p>
<p>At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into <code>json</code>.</p>
<p>When deserializing data, you always need to call <code>is_valid()</code> before attempting to access the deserialized object. If any validation errors occur, the <code>.errors</code> and <code>.non_field_errors</code> properties will contain the resulting error messages.</p>
<p><strong>TODO: Describe validation in more depth</strong></p>
<h2id="dealing-with-nested-objects">Dealing with nested objects</h2>
<p>The previous example is fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects,
where some of the attributes of an object might not be simple datatypes such as strings, dates or integers.</p>
<p>The <code>Serializer</code> class is itself a type of <code>Field</code>, and can be used to represent relationships where one object type is nested inside another.</p>
<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 intial datatype, and a primative, serializable datatype. Primative 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 primative objects.</p>
<p>The <code>.to_native()</code> method is called to convert the initial datatype into a primative, serializable datatype. The <code>from_native()</code> method is called to restore a primative datatype into it's initial representation.</p>
<p>Let's look at an example of serializing a class that represents an RGB color value:</p>
<pre><code>class Color(object):
"""
A color represented in the RGB colorspace.
"""
def __init__(self, red, green, blue):
assert(red >= 0 and green >= 0 and blue >= 0)
assert(red < 256 and green < 256 and blue < 256)
self.red, self.green, self.blue = red, green, blue
class ColourField(Field):
"""
Color objects are serialized into "rgb(#, #, #)" notation.
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>
<pre><code>class ClassNameField(Field):
def field_to_native(self, obj, field_name):
"""
Serialize the object's class name, not an attribute of the object.
<p>You can add extra fields to a <code>ModelSerializer</code> or override the default fields by declaring fields on the class, just as you would for a <code>Serializer</code> class.</p>
<p>Extra fields can corrospond to any property or callable on the model.</p>
<h2id="relational-fields">Relational fields</h2>
<p>When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation is to use the primary keys of the related instances.</p>
<p>Alternative representations include serializing using natural keys, serializing complete nested representations, or serializing using a custom representation, such as a URL that uniquely identifies the model instances.</p>
<p>The <code>PrimaryKeyField</code> and <code>NaturalKeyField</code> fields provide alternative flat representations.</p>
<p>The <code>ModelSerializer</code> class can itself be used as a field, in order to serialize relationships using nested representations.</p>
<p>The <code>RelatedField</code> class may be subclassed to create a custom represenation of a relationship. The subclass should override <code>.to_native()</code>, and optionally <code>.from_native()</code> if deserialization is supported.</p>
<p>All the relational fields may be used for any relationship or reverse relationship on a model.</p>
<h2id="specifying-which-fields-should-be-included">Specifying which fields should be included</h2>
<p>If you only want a subset of the default fields to be used in a model serializer, you can do so using <code>fields</code> or <code>exclude</code> options, just as you would with a <code>ModelForm</code>.</p>
<p>The <code>fields</code> and <code>exclude</code> options may also be set by passing them to the <code>serialize()</code> method.</p>
<p><strong>[TODO: Possibly only allow .serialize(fields=…) in FixtureSerializer for backwards compatability, but remove for ModelSerializer]</strong></p>
<p>The default <code>ModelSerializer</code> uses primary keys for relationships, but you can also easily generate nested representations using the <code>nested</code> option:</p>
<p>The <code>nested</code> option may be set to either <code>True</code>, <code>False</code>, or an integer value. If given an integer value it indicates the depth of relationships that should be traversed before reverting to a flat representation.</p>
<p>When serializing objects using a nested representation any occurances of recursion will be recognised, and will fall back to using a flat representation.</p>
<p>The <code>nested</code> option may also be set by passing it to the <code>serialize()</code> method.</p>
<p><strong>[TODO: Possibly only allow .serialize(nested=…) in FixtureSerializer]</strong></p>
<h2id="customising-the-default-fields-used-by-a-modelserializer">Customising the default fields used by a ModelSerializer</h2>