<p><strong>Note</strong>: This is the documentation for the <strong>version 3.0</strong> of REST framework. Documentation for <ahref="http://tomchristie.github.io/rest-framework-2-docs/">version 2.4</a> is also available.</p>
<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>The serializers in REST framework work very similarly to Django's <code>Form</code> and <code>ModelForm</code> classes. We provide 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>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>If we want to be able to return complete object instances based on the validated data we need to implement one or both of the <code>.create()</code> and <code>update()</code> methods. For example:</p>
<p>If your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if <code>Comment</code> was a Django model, the methods might look like this:</p>
<p>Calling <code>.save()</code> will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class:</p>
<pre><code># .save() will create a new instance.
serializer = CommentSerializer(data=data)
# .save() will update the existing `comment` instance.
<p>Both the <code>.create()</code> and <code>.update()</code> methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class.</p>
<h4id="passing-additional-attributes-to-save">Passing additional attributes to <code>.save()</code></h4>
<p>Sometimes you'll want your view code to be able to inject additional data at the point of saving the instance. This additional data might include information like the current user, the current time, or anything else that is not part of the request data.</p>
<p>You can do so by including additional keyword arguments when calling <code>.save()</code>. For example:</p>
<pre><code>serializer.save(owner=request.user)
</code></pre>
<p>Any additional keyword arguments will be included in the <code>validated_data</code> argument when <code>.create()</code> or <code>.update()</code> are called.</p>
<p>In some cases the <code>.create()</code> and <code>.update()</code> method names may not be meaningful. For example, in a contact form we may not be creating new instances, but instead sending an email or other message.</p>
<p>In these cases you might instead choose to override <code>.save()</code> directly, as being more readable and meaningful.</p>
<p>When deserializing data, you always need to call <code>is_valid()</code> before attempting to access the validated data, or save an object instance. If any validation errors occur, the <code>.errors</code> property will contain a dictionary representing the resulting error messages. For example:</p>
<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. The name of the <code>non_field_errors</code> key may be customized using the <code>NON_FIELD_ERRORS_KEY</code> REST framework setting.</p>
<h4id="raising-an-exception-on-invalid-data">Raising an exception on invalid data</h4>
<p>The <code>.is_valid()</code> method takes an optional <code>raise_exception</code> flag that will cause it to raise a <code>serializers.ValidationError</code> exception if there are validation errors.</p>
<p>These exceptions are automatically dealt with by the default exception handler that REST framework provides, and will return <code>HTTP 400 Bad Request</code> responses by default.</p>
<pre><code># Return a 400 response if the data was invalid.
<p>You can specify custom field-level validation by adding <code>.validate_<field_name></code> methods to your <code>Serializer</code> subclass. These are similar to the <code>.clean_<field_name></code> methods on Django forms.</p>
<p>These methods take a single argument, which is the field value that requires validation.</p>
<p>Your <code>validate_<field_name></code> methods should return the validated value or raise a <code>serializers.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 a dictionary of field values. It should raise a <code>ValidationError</code> if necessary, or just return the validated values. For example:</p>
<p>Serializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner <code>Meta</code> class, like so:</p>
<p>For more information see the <ahref="../validators">validators documentation</a>.</p>
<h2id="partial-updates">Partial updates</h2>
<p>By default, serializers must be passed values for all required fields or they will raise validation errors. You can use the <code>partial</code> argument in order to allow partial updates.</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>When dealing with nested representations that support deserializing the data, an errors with nested objects will be nested under the field name of the nested object.</p>
<p>Similarly, the <code>.validated_data</code> property will include nested data structures.</p>
<h4id="writing-create-methods-for-nested-representations">Writing <code>.create()</code> methods for nested representations</h4>
<p>If you're supporting writable nested representations you'll need to write <code>.create()</code> or <code>.update()</code> methods that handle saving multiple objects.</p>
<p>The following example demonstrates how you might handle creating a user with a nested profile object.</p>
<h4id="writing-update-methods-for-nested-representations">Writing <code>.update()</code> methods for nested representations</h4>
<p>For updates you'll want to think carefully about how to handle updates to relationships. For example if the data for the relationship is <code>None</code>, or not provided, which of the following should occur?</p>
<ul>
<li>Set the relationship to <code>NULL</code> in the database.</li>
<li>Delete the associated instance.</li>
<li>Ignore the data and leave the instance as it is.</li>
<li>Raise a validation error.</li>
</ul>
<p>Here's an example for an <code>update()</code> method on our previous <code>UserSerializer</code> class.</p>
<p>Because the behavior of nested creates and updates can be ambiguous, and may require complex dependancies between related models, REST framework 3 requires you to always write these methods explicitly. The default <code>ModelSerializer</code><code>.create()</code> and <code>.update()</code> methods do not include support for writable nested representations.</p>
<p>It is possible that a third party package, providing automatic support some kinds of automatic writable nested representations may be released alongside the 3.1 release.</p>
<h4id="handling-saving-related-instances-in-model-manager-classes">Handling saving related instances in model manager classes</h4>
<p>An alternative to saving multiple related instances in the serializer is to write custom model manager classes handle creating the correct instances.</p>
<p>For example, suppose we wanted to ensure that <code>User</code> instances and <code>Profile</code> instances are always created together as a pair. We might write a custom manager class that looks something like this:</p>
<p>This manager class now more nicely encapsulates that user instances and profile instances are always created at the same time. Our <code>.create()</code> method on the serializer class can now be re-written to use the new manager method.</p>
<p>For more details on this approach see the Django documentation on <ahref="../../model-managers">model managers</a>, and <ahref="../../encapsulation-blogpost">this blogpost on using model and manger classes</a>.</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>
<p>The default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the <ahref="#ListSerializer">ListSerializer</a> documentation below.</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_representation()</code> method, by accessing the <code>self.context</code> attribute.</p>
<p>Often you'll want serializer classes that map closely to Django model definitions.</p>
<p>The <code>ModelSerializer</code> class provides a shortcut that lets you automatically create a <code>Serializer</code> class with fields that correspond to the Model fields.</p>
<p><strong>The <code>ModelSerializer</code> class is the same as a regular <code>Serializer</code> class, except that</strong>:</p>
<ul>
<li>It will automatically generate a set of fields for you, based on the model.</li>
<li>It will automatically generate validators for the serializer, such as unique_together validators.</li>
<li>It includes simple default implementations of <code>.create()</code> and <code>.update()</code>.</li>
</ul>
<p>Declaring a <code>ModelSerializer</code> looks like this:</p>
<p>By default, all the model fields on the class will be mapped to a corresponding serializer fields.</p>
<p>Any relationships such as foreign keys on the model will be mapped to <code>PrimaryKeyRelatedField</code>. Reverse relationships are not included by default unless explicitly included as described below.</p>
<h4id="inspecting-a-modelserializer">Inspecting a <code>ModelSerializer</code></h4>
<p>Serializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with <code>ModelSerializers</code> where you want to determine what set of fields and validators are being automatically created for you.</p>
<p>To do so, open the Django shell, using <code>python manage.py shell</code>, then import the serializer class, instantiate it, and print the object representation…</p>
<pre><code>>>> from myapp.serializers import AccountSerializer
>>> serializer = AccountSerializer()
>>> print repr(serializer) # Or `print(repr(serializer))` in Python 3.x.
AccountSerializer():
id = IntegerField(label='ID', read_only=True)
name = CharField(allow_blank=True, max_length=100, required=False)
<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>
<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>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 shortcut Meta option, <code>read_only_fields</code>.</p>
<p>This option should be a list or tuple of field names, and is declared as follows:</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>
<p><strong>Note</strong>: There is a special-case where a read-only field is part of a <code>unique_together</code> constraint at the model level. In this case the field is required by the serializer class in order to validate the constraint, but should also not be editable by the user.</p>
<p>The right way to deal with this is to specify the field explicitly on the serializer, providing both the <code>read_only=True</code> and <code>default=…</code> keyword arguments.</p>
<p>One example of this is a read-only relation to the currently authenticated <code>User</code> which is <code>unique_together</code> with another identifier. In this case you would declare the user field like so:</p>
<p>Please review the <ahref="../..//api-guide/validators/">Validators Documentation</a> for details on the <ahref="../..//api-guide/validators/#uniquetogethervalidator">UniqueTogetherValidator</a> and <ahref="../..//api-guide/validators/#currentuserdefault">CurrentUserDefault</a> classes.</p>
<h2id="specifying-additional-keyword-arguments-for-fields">Specifying additional keyword arguments for fields.</h2>
<p>There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the <code>extra_kwargs</code> option. Similarly to <code>read_only_fields</code> this means you do not need to explicitly declare the field on the serializer.</p>
<p>This option is a dictionary, mapping field names to a dictionary of keyword arguments. For example:</p>
<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 inner <code>Meta</code> class on serializers is not inherited from parent classes by default. This is the same behavior as with Django's <code>Model</code> and <code>ModelForm</code> classes. If you want the <code>Meta</code> class to inherit from a parent class you must do so explicitly. For example:</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 override a URL field view name and lookup field by using either, or both of, the <code>view_name</code> and <code>lookup_field</code> options in the <code>extra_kwargs</code> setting, like so:</p>
<p><strong>Tip</strong>: Properly matching together hyperlinked representations and your URL conf can sometimes be a bit fiddly. Printing the <code>repr</code> of a <code>HyperlinkedModelSerializer</code> instance is a particularly useful way to inspect exactly which view names and lookup fields the relationships are expected to map too.</p>
<hr/>
<h2id="changing-the-url-field-name">Changing the URL field name</h2>
<p>The <code>ListSerializer</code> class provides the behavior for serializing and validating multiple objects at once. You won't <em>typically</em> need to use <code>ListSerializer</code> directly, but should instead simply pass <code>many=True</code> when instantiating a serializer.</p>
<p>When a serializer is instantiated and <code>many=True</code> is passed, a <code>ListSerializer</code> instance will be created. The serializer class then becomes a child of the parent <code>ListSerializer</code></p>
<p>There <em>are</em> a few use cases when you might want to customize the <code>ListSerializer</code> behavior. For example:</p>
<ul>
<li>You want to provide particular validation of the lists, such as always ensuring that there is at least one element in a list.</li>
<li>You want to customize the create or update behavior of multiple objects.</li>
</ul>
<p>For these cases you can modify the class that is used when <code>many=True</code> is passed, by using the <code>list_serializer_class</code> option on the serializer <code>Meta</code> class.</p>
<p>The default implementation for multiple object creation is to simply call <code>.create()</code> for each item in the list. If you want to customize this behavior, you'll need to customize the <code>.create()</code> method on <code>ListSerializer</code> class that is used when <code>many=True</code> is passed.</p>
<p>By default the <code>ListSerializer</code> class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous.</p>
<p>To support multiple updates you'll need to do so explicitly. When writing your multiple update code make sure to keep the following in mind:</p>
<ul>
<li>How do you determine which instance should be updated for each item in the list of data?</li>
<li>How should insertions be handled? Are they invalid, or do they create new objects?</li>
<li>How should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid?</li>
book_mapping = {book.id: book for book in instance}
data_mapping = {item['id']: item for item in validated_data}
# Perform creations and updates.
ret = []
for book_id, data in data_mapping.items():
book = book_mapping.get(book_id, None):
if book is None:
ret.append(self.child.create(data))
else:
ret.append(self.child.update(book, data))
# Perform deletions.
for book_id, book in book_mapping.items():
if book_id not in data_mapping:
book.delete()
return ret
class BookSerializer(serializers.Serializer):
...
class Meta:
list_serializer_class = BookListSerializer
</code></pre>
<p>It is possible that a third party package may be included alongside the 3.1 release that provides some automatic support for multiple update operations, similar to the <code>allow_add_remove</code> behavior that was present in REST framework 2.</p>
<p>When a serializer with <code>many=True</code> is instantiated, we need to determine which arguments and keyword arguments should be passed to the <code>.__init__()</code> method for both the child <code>Serializer</code> class, and for the parent <code>ListSerializer</code> class.</p>
<p>The default implementation is to pass all arguments to both classes, except for <code>validators</code>, and any custom keyword arguments, both of which are assumed to be intended for the child serializer class.</p>
<p>Occasionally you might need to explicitly specify how the child and parent classes should be instantiated when <code>many=True</code> is passed. You can do so by using the <code>many_init</code> class method.</p>
<p><code>BaseSerializer</code> class that can be used to easily support alternative serialization and deserialization styles.</p>
<p>This class implements the same basic API as the <code>Serializer</code> class:</p>
<ul>
<li><code>.data</code> - Returns the outgoing primitive representation.</li>
<li><code>.is_valid()</code> - Deserializes and validates incoming data.</li>
<li><code>.validated_data</code> - Returns the validated incoming data.</li>
<li><code>.errors</code> - Returns an errors during validation.</li>
<li><code>.save()</code> - Persists the validated data into an object instance.</li>
</ul>
<p>There are four methods that can be overridden, depending on what functionality you want the serializer class to support:</p>
<ul>
<li><code>.to_representation()</code> - Override this to support serialization, for read operations.</li>
<li><code>.to_internal_value()</code> - Override this to support deserialization, for write operations.</li>
<li><code>.create()</code> and <code>.update()</code> - Overide either or both of these to support saving instances.</li>
</ul>
<p>Because this class provides the same interface as the <code>Serializer</code> class, you can use it with the existing generic class based views exactly as you would for a regular <code>Serializer</code> or <code>ModelSerializer</code>.</p>
<p>The only difference you'll notice when doing so is the <code>BaseSerializer</code> classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input.</p>
<p>To implement a read-only serializer using the <code>BaseSerializer</code> class, we just need to override the <code>.to_representation()</code> method. Let's take a look at an example using a simple Django model:</p>
<pre><code>class HighScore(models.Model):
created = models.DateTimeField(auto_now_add=True)
player_name = models.CharField(max_length=10)
score = models.IntegerField()
</code></pre>
<p>It's simple to create a read-only serializer for converting <code>HighScore</code> instances into primitive data types.</p>
<p>To create a read-write serializer we first need to implement a <code>.to_internal_value()</code> method. This method returns the validated values that will be used to construct the object instance, and may raise a <code>ValidationError</code> if the supplied data is in an incorrect format.</p>
<p>Once you've implemented <code>.to_internal_value()</code>, the basic validation API will be available on the serializer, and you will be able to use <code>.is_valid()</code>, <code>.validated_data</code> and <code>.errors</code>.</p>
<p>If you want to also support <code>.save()</code> you'll need to also implement either or both of the <code>.create()</code> and <code>.update()</code> methods.</p>
<p>Here's a complete example of our previous <code>HighScoreSerializer</code>, that's been updated to support both read and write operations.</p>
'player_name': 'May not be more than 10 characters.'
})
# Return the validated values. This will be available as
# the `.validated_data` property.
return {
'score': int(score),
'player_name': player_name
}
def to_representation(self, obj):
return {
'score': obj.score,
'player_name': obj.player_name
}
def create(self, validated_data):
return HighScore.objects.create(**validated_data)
</code></pre>
<h4id="creating-new-base-classes">Creating new base classes</h4>
<p>The <code>BaseSerializer</code> class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends.</p>
<p>The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.</p>
<h2id="overriding-serialization-and-deserialization-behavior">Overriding serialization and deserialization behavior</h2>
<p>If you need to alter the serialization, deserialization or validation of a serializer class you can do so by overriding the <code>.to_representation()</code> or <code>.to_internal_value()</code> methods.</p>
<p>Some reasons this might be useful include...</p>
<ul>
<li>Adding new behavior for new serializer base classes.</li>
<li>Modifying the behavior slightly for an existing class.</li>
<li>Improving serialization performance for a frequently accessed API endpoint that returns lots of data.</li>
</ul>
<p>The signatures for these methods are as follows:</p>
<p>Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.</p>
<p>Takes the unvalidated incoming data as input and should return the validated data that will be made available as <code>serializer.validated_data</code>. The return value will also be passed to the <code>.create()</code> or <code>.update()</code> methods if <code>.save()</code> is called on the serializer class.</p>
<p>If any of the validation fails, then the method should raise a <code>serializers.ValidationError(errors)</code>. Typically the <code>errors</code> argument here will be a dictionary mapping field names to error messages.</p>
<p>The <code>data</code> argument passed to this method will normally be the value of <code>request.data</code>, so the datatype it provides will depend on the parser classes you have configured for your API.</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="customizing-the-default-fields">Customizing the default fields</h2>
<p>REST framework 2 provided an API to allow developers to override how a <code>ModelSerializer</code> class would automatically generate the default set of fields.</p>
<p>This API included the <code>.get_field()</code>, <code>.get_pk_field()</code> and other methods.</p>
<p>Because the serializers have been fundamentally redesigned with 3.0 this API no longer exists. You can still modify the fields that get created but you'll need to refer to the source code, and be aware that if the changes you make are against private bits of API then they may be subject to change.</p>
<p>A new interface for controlling this behavior is currently planned for REST framework 3.1.</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>