<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.</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.</p>
<p>The <code>restore_object</code> method is optional, and is only required if we want our serializer to support deserialization into fully fledged object instances. If we don't define this method, then deserializing data will simply return a dictionary of items.</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>
<h3id="customizing-field-representation">Customizing field representation</h3>
<p>Sometimes when serializing objects, you may not want to represent everything exactly the way it is in your model.</p>
<p>If you need to customize the serialized value of a particular field, you can do this by creating a <code>transform_<fieldname></code> method. For example if you needed to render some markdown from a text field:</p>
<p>By default, serializers must be passed values for all required fields or they will throw validation errors. You can use the <code>partial</code> argument in order to allow partial updates.</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> property will contain a dictionary representing the resulting error messages. For example:</p>
# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}
</code></pre>
<p>Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The <code>non_field_errors</code> key may also be present, and will list any general validation errors.</p>
<p>When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.</p>
<p>You can specify custom field-level validation by adding <code>.validate_<fieldname></code> methods to your <code>Serializer</code> subclass. These are analogous to <code>.clean_<fieldname></code> methods on Django forms, but accept slightly different arguments.</p>
<p>They take a dictionary of deserialized attributes as a first argument, and the field name in that dictionary as a second argument (which will be either the name of the field or the value of the <code>source</code> argument to the field, if one was provided).</p>
<p>Your <code>validate_<fieldname></code> methods should either just return the <code>attrs</code> dictionary or raise a <code>ValidationError</code>. For example:</p>
<p>To do any other validation that requires access to multiple fields, add a method called <code>.validate()</code> to your <code>Serializer</code> subclass. This method takes a single argument, which is the <code>attrs</code> dictionary. It should raise a <code>ValidationError</code> if necessary, or just return <code>attrs</code>. For example:</p>
<p>The default behavior of the method is to simply call <code>.save()</code> on the deserialized object instance. You can override the default save behaviour by overriding the <code>.save_object(obj)</code> method on the serializer class.</p>
<p>The generic views provided by REST framework call the <code>.save()</code> method when updating or creating entities. </p>
<h2id="dealing-with-nested-objects">Dealing with nested objects</h2>
<p>The previous examples are 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 a nested representation may optionally accept the <code>None</code> value you should pass the <code>required=False</code> flag to the nested serializer.</p>
<p>To serialize a queryset or list of objects instead of a single object instance, you should pass the <code>many=True</code> flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.</p>
<h4id="deserializing-multiple-objects-for-creation">Deserializing multiple objects for creation</h4>
<p>To deserialize a list of object data, and create multiple object instances in a single pass, you should also set the <code>many=True</code> flag, and pass a list of data to be deserialized.</p>
<p>This allows you to write views that create multiple items when a <code>POST</code> request is made.</p>
<p>For example:</p>
<preclass="prettyprint lang-py"><code>data = [
{'title': 'The bell jar', 'author': 'Sylvia Plath'},
{'title': 'For whom the bell tolls', 'author': 'Ernest Hemingway'}
]
serializer = BookSerializer(data=data, many=True)
serializer.is_valid()
# True
serializer.save() # `.save()` will be called on each deserialized instance
</code></pre>
<h4id="deserializing-multiple-objects-for-update">Deserializing multiple objects for update</h4>
<p>You can also deserialize a list of objects as part of a bulk update of multiple existing items.
In this case you need to supply both an existing list or queryset of items, as well as a list of data to update those items with.</p>
<p>This allows you to write views that update or create multiple items when a <code>PUT</code> request is made.</p>
<preclass="prettyprint lang-py"><code># Capitalizing the titles of the books
queryset = Book.objects.all()
data = [
{'id': 3, 'title': 'The Bell Jar', 'author': 'Sylvia Plath'},
{'id': 4, 'title': 'For Whom the Bell Tolls', 'author': 'Ernest Hemingway'}
serializer.save() # `.save()` will be called on each updated or newly created instance.
</code></pre>
<p>By default bulk updates will be limited to updating instances that already exist in the provided queryset.</p>
<p>When performing a bulk update you may want to allow new items to be created, and missing items to be deleted. To do so, pass <code>allow_add_remove=True</code> to the serializer.</p>
serializer.save() # `.save()` will be called on updated or newly created instances.
#`.delete()` will be called on any other items in the `queryset`.
</code></pre>
<p>Passing <code>allow_add_remove=True</code> ensures that any update operations will completely overwrite the existing queryset, rather than simply updating existing objects.</p>
<h4id="how-identity-is-determined-when-performing-bulk-updates">How identity is determined when performing bulk updates</h4>
<p>Performing a bulk update is slightly more complicated than performing a bulk creation, because the serializer needs a way to determine how the items in the incoming data should be matched against the existing object instances.</p>
<p>By default the serializer class will use the <code>id</code> key on the incoming data to determine the canonical identity of an object. If you need to change this behavior you should override the <code>get_identity</code> method on the <code>Serializer</code> class. For example:</p>
We need to override the default, to use the slug as the identity.
Note that the data has not yet been validated at this point,
so we need to deal gracefully with incorrect datatypes.
"""
try:
return data.get('slug', None)
except AttributeError:
return None
</code></pre>
<p>To map the incoming data items to their corresponding object instances, the <code>.get_identity()</code> method will be called both against the incoming data, and against the serialized representation of the existing objects.</p>
<h2id="including-extra-context">Including extra context</h2>
<p>There are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs.</p>
<p>You can provide arbitrary additional context by passing a <code>context</code> argument when instantiating the serializer. For example:</p>
<p>The context dictionary can be used within any serializer field logic, such as a custom <code>.to_native()</code> method, by accessing the <code>self.context</code> attribute.</p>
<p>-</p>
<h1id="modelserializer">ModelSerializer</h1>
<p>Often you'll want serializer classes that map closely to model definitions.
The <code>ModelSerializer</code> class lets you automatically create a Serializer class with fields that correspond to the Model fields.</p>
<p>By default, all the model fields on the class will be mapped to corresponding serializer fields.</p>
<p>Any relationships such as foreign keys on the model will be mapped to <code>PrimaryKeyRelatedField</code>. Other models fields will be mapped to a corresponding serializer field.</p>
<hr/>
<p><strong>Note</strong>: When validation is applied to a <code>ModelSerializer</code>, both the serializer fields, and their corresponding model fields must correctly validate. If you have optional fields on your model, make sure to correctly set <code>blank=True</code> on the model field, as well as setting <code>required=False</code> on the serializer field.</p>
<hr/>
<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 default <code>ModelSerializer</code> uses primary keys for relationships, but you can also easily generate nested representations using the <code>depth</code> option:</p>
<p>The <code>depth</code> option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.</p>
<p>If you want to customize the way the serialization is done (e.g. using <code>allow_add_remove</code>) you'll need to define the field yourself.</p>
<h2id="specifying-which-fields-should-be-read-only">Specifying which fields should be read-only</h2>
<p>You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the <code>read_only=True</code> attribute, you may use the <code>read_only_fields</code> Meta option, like so:</p>
<p>Model fields which have <code>editable=False</code> set, and <code>AutoField</code> fields will be set to read-only by default, and do not need to be added to the <code>read_only_fields</code> option. </p>
<h2id="specifying-which-fields-should-be-write-only">Specifying which fields should be write-only</h2>
<p>You may wish to specify multiple fields as write-only. Instead of adding each field explicitly with the <code>write_only=True</code> attribute, you may use the <code>write_only_fields</code> Meta option, like so:</p>
<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>
groups = serializers.PrimaryKeyRelatedField(many=True)
class Meta:
model = Account
</code></pre>
<p>Extra fields can correspond 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 for <code>ModelSerializer</code> is to use the primary keys of the related instances.</p>
<p>Alternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation.</p>
<p>The <code>HyperlinkedModelSerializer</code> class is similar to the <code>ModelSerializer</code> class except that it uses hyperlinks to represent relationships, rather than primary keys.</p>
<p>By default the serializer will include a <code>url</code> field instead of a primary key field.</p>
<p>The url field will be represented using a <code>HyperlinkedIdentityField</code> serializer field, and any relationships on the model will be represented using a <code>HyperlinkedRelatedField</code> serializer field.</p>
<p>You can explicitly include the primary key by adding it to the <code>fields</code> option, for example:</p>
<h2id="how-hyperlinked-views-are-determined">How hyperlinked views are determined</h2>
<p>There needs to be a way of determining which views should be used for hyperlinking to model instances.</p>
<p>By default hyperlinks are expected to correspond to a view name that matches the style <code>'{model_name}-detail'</code>, and looks up the instance by a <code>pk</code> keyword argument.</p>
<p>You can change the field that is used for object lookups by setting the <code>lookup_field</code> option. The value of this option should correspond both with a kwarg in the URL conf, and with a field on the model. For example:</p>
<p>Note that the <code>lookup_field</code> will be used as the default on <em>all</em> hyperlinked fields, including both the URL identity, and any hyperlinked relationships.</p>
<p>For more specific requirements such as specifying a different lookup for each field, you'll want to set the fields on the serializer explicitly. For example:</p>
<p><strong>Note</strong>: The generic view implementations normally generate a <code>Location</code> header in response to successful <code>POST</code> requests. Serializers using <code>url_field_name</code> option will not have this header automatically included by the view. If you need to do so you will ned to also override the view's <code>get_success_headers()</code> method.</p>
<p>You can also override the URL field's view name and lookup field without overriding the field explicitly, by using the <code>view_name</code> and <code>lookup_field</code> options, like so:</p>
<p>You can create customized subclasses of <code>ModelSerializer</code> or <code>HyperlinkedModelSerializer</code> that use a different set of default fields.</p>
<p>Doing so should be considered advanced usage, and will only be needed if you have some particular serializer requirements that you often need to repeat.</p>
<p>Once a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the <code>.fields</code> attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer.</p>
<p>Modifying the <code>fields</code> argument directly allows you to do interesting things such as changing the arguments on serializer fields at runtime, rather than at the point of declaring the serializer.</p>
<h3id="example">Example</h3>
<p>For example, if you wanted to be able to set which fields should be used by a serializer at the point of initializing it, you could create a serializer class like so:</p>
<h2id="customising-the-default-fields">Customising the default fields</h2>
<p>The <code>field_mapping</code> attribute is a dictionary that maps model classes to serializer classes. Overriding the attribute will let you set a different set of default serializer classes. </p>
<p>For more advanced customization than simply changing the default serializer class you can override various <code>get_<field_type>_field</code> methods. Doing so will allow you to customize the arguments that each serializer field is initialized with. Each of these methods may either return a field or serializer instance, or <code>None</code>.</p>
<p>Returns the field instance that should be used to represent a related field when <code>depth</code> is specified as being non-zero.</p>
<p>Note that the <code>model_field</code> argument will be <code>None</code> for reverse relationships. The <code>related_model</code> argument will be the model class for the target of the field. The <code>to_many</code> argument will be a boolean indicating if this is a to-one or to-many relationship.</p>
<p>Returns the field instance that should be used to represent a related field when <code>depth</code> is not specified, or when nested representations are being used and the depth reaches zero.</p>
<p>Note that the <code>model_field</code> argument will be <code>None</code> for reverse relationships. The <code>related_model</code> argument will be the model class for the target of the field. The <code>to_many</code> argument will be a boolean indicating if this is a to-one or to-many relationship.</p>
<p>The <ahref="https://github.com/umutbozkurt/django-rest-framework-mongoengine">django-rest-framework-mongoengine</a> package provides a <code>MongoEngineModelSerializer</code> serializer class that supports using MongoDB as the storage layer for Django REST framework.</p>
<p>The <ahref="https://github.com/djangonauts/django-rest-framework-gis">django-rest-framework-gis</a> package provides a <code>GeoFeatureModelSerializer</code> serializer class that supports GeoJSON both for read and write operations.</p>
<p>The <ahref="https://github.com/djangonauts/django-rest-framework-hstore">django-rest-framework-hstore</a> package provides an <code>HStoreSerializer</code> to support <ahref="https://github.com/djangonauts/django-hstore">django-hstore</a><code>DictionaryField</code> model field and its <code>schema-mode</code> feature.</p>