Raised if there are no parsers that can handle the content type of the request data when accessing request.DATA or request.FILES.
+
Raised if there are no parsers that can handle the content type of the request data when accessing request.data.
By default this exception results in a response with the HTTP status code "415 Unsupported Media Type".
Throttled
Signature:Throttled(wait=None, detail=None)
Raised when an incoming request fails the throttling checks.
By default this exception results in a response with the HTTP status code "429 Too Many Requests".
+
ValidationError
+
Signature:ValidationError(detail)
+
The ValidationError exception is slightly different from the other APIException classes:
+
+
The detail argument is mandatory, not optional.
+
The detail argument may be a list or dictionary of error details, and may also be a nested data structure.
+
By convention you should import the serializers module and use a fully qualified ValidationError style, in order to differentiate it from Django's built-in validation error. For example. raise serializers.ValidationError('This field must be an integer value.')
+
+
The ValidationError class should be used for serializer and field validation, and by validator classes. It is also raised when calling serializer.is_valid with the raise_exception keyword argument:
+
serializer.is_valid(raise_exception=True)
+
+
The generic views use the raise_exception=True flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.
+
By default this exception results in a response with the HTTP status code "400 Bad Request".
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.
-
Note: The serializer fields are declared in fields.py, but by convention you should import them using from rest_framework import serializers and refer to fields as serializers.<FieldName>.
+
Note: The serializer fields are declared in fields.py, but by convention you should import them using from rest_framework import serializers and refer to fields as serializers.<FieldName>.
Core arguments
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:
-
source
-
The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as Field(source='get_absolute_url'), or may use dotted notation to traverse attributes, such as Field(source='user.email').
-
The value source='*' 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 PaginationSerializer class for an example.)
-
Defaults to the name of the field.
read_only
Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.
Defaults to False
@@ -517,111 +588,135 @@
Normally an error will be raised if a field is not supplied during deserialization.
Set to false if this field is not required to be present during deserialization.
Defaults to True.
+
allow_null
+
Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value.
+
Defaults to False
default
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.
May be set to a function or other callable, in which case the value will be evaluated each time it is used.
+
Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error.
+
source
+
The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField('get_absolute_url'), or may use dotted notation to traverse attributes, such as EmailField(source='user.email').
+
The value source='*' 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.
+
Defaults to the name of the field.
validators
-
A list of Django validators that should be used to validate deserialized values.
+
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 serializers.ValidationError, but Django's built-in ValidationError is also supported for compatibility with validators defined in the Django codebase or third party Django packages.
error_messages
A dictionary of error codes to error messages.
-
widget
-
Used only if rendering the field to HTML.
-This argument sets the widget that should be used to render the field. For more details, and a list of available widgets, see the Django documentation on form widgets.
label
A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.
help_text
A text string that may be used as a description of the field in HTML form fields or other descriptive elements.
-
-
Generic Fields
-
These generic fields are used for representing arbitrary model fields or the output of model methods.
-
Field
-
A generic, read-only field. You can use this field for any attribute that does not need to support write operations.
-
For example, using the following model.
-
from django.db import models
-from django.utils.timezone import now
+
initial
+
A value that should be used for pre-populating the value of HTML form fields.
+
style
+
A dictionary of key-value pairs that can be used to control how renderers should render the field. The API for this should still be considered experimental, and will be formalized with the 3.1 release.
+
Two options are currently used in HTML form generation, 'input_type' and 'base_template'.
+
# Use <input type="password"> for the input.
+password = serializers.CharField(
+ style={'input_type': 'password'}
+)
-class Account(models.Model):
- owner = models.ForeignKey('auth.user')
- name = models.CharField(max_length=100)
- created = models.DateTimeField(auto_now_add=True)
- payment_expiry = models.DateTimeField()
-
- def has_expired(self):
- return now() > self.payment_expiry
-
-
A serializer definition that looked like this:
-
from rest_framework import serializers
-
-class AccountSerializer(serializers.HyperlinkedModelSerializer):
- expired = serializers.Field(source='has_expired')
-
- class Meta:
- model = Account
- fields = ('url', 'owner', 'name', 'expired')
-
-
Would produce output similar to:
-
{
- 'url': 'http://example.com/api/accounts/3/',
- 'owner': 'http://example.com/api/users/12/',
- 'name': 'FooCorp business account',
- 'expired': True
+# Use a radio input instead of a select input.
+color_channel = serializers.ChoiceField(
+ choices=['red', 'green', 'blue']
+ style = {'base_template': 'radio.html'}
}
-
By default, the Field class will perform a basic translation of the source value into primitive datatypes, falling back to unicode representations of complex datatypes when necessary.
-
You can customize this behavior by overriding the .to_native(self, value) method.
-
WritableField
-
A field that supports both read and write operations. By itself WritableField 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 .to_native(self, value) and .from_native(self, value) methods.
-
ModelField
-
A generic field that can be tied to any arbitrary model field. The ModelField 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.
-
The ModelField class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a ModelField, it must be passed a field that is attached to an instantiated model. For example: ModelField(model_field=MyModel()._meta.get_field('custom_field'))
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 self), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
-
from django.contrib.auth.models import User
-from django.utils.timezone import now
-from rest_framework import serializers
-
-class UserSerializer(serializers.ModelSerializer):
- days_since_joined = serializers.SerializerMethodField('get_days_since_joined')
-
- class Meta:
- model = User
-
- def get_days_since_joined(self, obj):
- return (now() - obj.date_joined).days
-
+
Note: The style argument replaces the old-style version 2.x widget keyword argument. Because REST framework 3 now uses templated HTML form generation, the widget option that was used to support Django built-in widgets can no longer be supported. Version 3.1 is planned to include public API support for customizing HTML form generation.
-
Typed Fields
-
These fields represent basic datatypes, and support both reading and writing values.
+
Boolean fields
BooleanField
-
A Boolean representation.
+
A boolean representation.
Corresponds to django.db.models.fields.BooleanField.
+
Signature:BooleanField()
+
NullBooleanField
+
A boolean representation that also accepts None as a valid value.
+
Corresponds to django.db.models.fields.NullBooleanField.
+
Signature:NullBooleanField()
+
+
String fields
CharField
-
A text representation, optionally validates the text to be shorter than max_length and longer than min_length.
-If allow_none is False (default), None values will be converted to an empty string.
-
Corresponds to django.db.models.fields.CharField
-or django.db.models.fields.TextField.
A field that can accept a value out of a limited set of choices. Optionally takes a blank_display_value parameter that customizes the display value of an empty choice.
max_length - Validates that the input contains no more than this number of characters.
+
min_length - Validates that the input contains no fewer than this number of characters.
+
allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False.
+
+
The allow_null option is also available for string fields, although its usage is discouraged in favor of allow_blank. It is valid to set both allow_blank=True and allow_null=True, 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.
EmailField
A text representation, validates the text to be a valid e-mail address.
Corresponds to django.db.models.fields.IntegerField, django.db.models.fields.SmallIntegerField, django.db.models.fields.PositiveIntegerField and django.db.models.fields.PositiveSmallIntegerField.
max_digits The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places.
+
decimal_places The number of decimal places to store with the number.
+
coerce_to_string Set to True if string values should be returned for the representation, or False if Decimal objects should be returned. Defaults to the same value as the COERCE_DECIMAL_TO_STRING settings key, which will be True unless overridden. If Decimal objects are returned by the serializer, then the final output format will be determined by the renderer.
+
max_value Validate that the number provided is no greater than this value.
+
min_value Validate that the number provided is no less than this value.
+
+
Example usage
+
To validate numbers up to 999 with a resolution of 2 decimal places, you would use:
This field also takes an optional argument, coerce_to_string. If set to True the representation will be output as a string. If set to False the representation will be left as a Decimal instance and the final representation will be determined by the renderer.
+
If unset, this will default to the same value as the COERCE_DECIMAL_TO_STRING setting, which is True unless set otherwise.
+
+
Date and time fields
DateTimeField
A date and time representation.
-
Corresponds to django.db.models.fields.DateTimeField
+
Corresponds to django.db.models.fields.DateTimeField.
format - A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python datetime objects should be returned by to_representation. In this case the datetime encoding will be determined by the renderer.
+
input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATETIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'].
+
+
DateTimeField format strings.
+
Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style datetimes should be used. (eg '2013-01-29T12:34:56.000000Z')
+
When a value of None is used for the format datetime objects will be returned by to_representation and the final output representation will determined by the renderer class.
+
In the case of JSON this means the default datetime representation uses the ECMA 262 date time string specification. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: 2013-01-29T12:34:56.123Z.
+
auto_now and auto_now_add model fields.
When using ModelSerializer or HyperlinkedModelSerializer, note that any model fields with auto_now=True or auto_now_add=True will use serializer fields that are read_only=True by default.
If you want to override this behavior, you'll need to declare the DateTimeField explicitly on the serializer. For example:
class CommentSerializer(serializers.ModelSerializer):
@@ -630,84 +725,134 @@ or django.db.models.fields.TextField.
class Meta:
model = Comment
-
Note that by default, datetime representations are determined by the renderer in use, although this can be explicitly overridden as detailed below.
-
In the case of JSON this means the default datetime representation uses the ECMA 262 date time string specification. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: 2013-01-29T12:34:56.123Z.
format - A string representing the output format. If not specified, this defaults to None, which indicates that Python datetime objects should be returned by to_native. In this case the datetime encoding will be determined by the renderer.
-
input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATETIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'].
-
-
DateTime format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style datetimes should be used. (eg '2013-01-29T12:34:56.000000Z')
format - A string representing the output format. If not specified, this defaults to None, which indicates that Python date objects should be returned by to_native. In this case the date encoding will be determined by the renderer.
+
format - A string representing the output format. If not specified, this defaults to the same value as the DATE_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python date objects should be returned by to_representation. In this case the date encoding will be determined by the renderer.
input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATE_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'].
-
Date format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style dates should be used. (eg '2013-01-29')
+
DateField format strings
+
Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style dates should be used. (eg '2013-01-29')
TimeField
A time representation.
-
Optionally takes format as parameter to replace the matching pattern.
format - A string representing the output format. If not specified, this defaults to None, which indicates that Python time objects should be returned by to_native. In this case the time encoding will be determined by the renderer.
+
format - A string representing the output format. If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python time objects should be returned by to_representation. In this case the time encoding will be determined by the renderer.
input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the TIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'].
-
Time format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style times should be used. (eg '12:34:56.000000')
-
IntegerField
-
An integer representation.
-
Corresponds to django.db.models.fields.IntegerField, django.db.models.fields.SmallIntegerField, django.db.models.fields.PositiveIntegerField and django.db.models.fields.PositiveSmallIntegerField
-
FloatField
-
A floating point representation.
-
Corresponds to django.db.models.fields.FloatField.
-
DecimalField
-
A decimal representation, represented in Python by a Decimal instance.
-
Has two required arguments:
+
TimeField format strings
+
Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style times should be used. (eg '12:34:56.000000')
+
+
Choice selection fields
+
ChoiceField
+
A field that can accept a value out of a limited set of choices.
+
Used by ModelSerializer to automatically generate fields if the corresponding model field includes a choices=… argument.
+
Signature:ChoiceField(choices)
-
-
max_digits The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places.
-
-
-
decimal_places The number of decimal places to store with the number.
-
+
choices - A list of valid values, or a list of (key, display_name) tuples.
-
For example, to validate numbers up to 999 with a resolution of 2 decimal places, you would use:
This field also takes an optional argument, coerce_to_string. If set to True the representation will be output as a string. If set to False the representation will be left as a Decimal instance and the final representation will be determined by the renderer.
-
If unset, this will default to the same value as the COERCE_DECIMAL_TO_STRING setting, which is True unless set otherwise.
Corresponds to django.db.models.fields.DecimalField.
+
MultipleChoiceField
+
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. to_internal_representation returns a set containing the selected values.
+
Signature:MultipleChoiceField(choices)
+
+
choices - A list of valid values, or a list of (key, display_name) tuples.
+
+
+
File upload fields
+
Parsers and file uploads.
+
The FileField and ImageField classes are only suitable for use with MultiPartParser or FileUploadParser. Most parsers, such as e.g. JSON don't support file uploads.
+Django's regular FILE_UPLOAD_HANDLERS are used for handling uploaded files.
FileField
A file representation. Performs Django's standard FileField validation.
max_length designates the maximum length for the file name.
-
-
-
allow_empty_file designates if empty files are allowed.
-
+
max_length - Designates the maximum length for the file name.
+
allow_empty_file - Designates if empty files are allowed.
+
use_url - If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise.
ImageField
-
An image representation.
+
An image representation. Validates the uploaded file content as matching a known image format.
max_length - Designates the maximum length for the file name.
+
allow_empty_file - Designates if empty files are allowed.
+
use_url - If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise.
+
Requires either the Pillow package or PIL package. The Pillow package is recommended, as PIL is no longer actively maintained.
-
Signature and validation is the same as with FileField.
-
Note:FileFields and ImageFields are only suitable for use with MultiPartParser, since e.g. json doesn't support file uploads.
-Django's regular FILE_UPLOAD_HANDLERS are used for handling uploaded files.
+
Composite fields
+
ListField
+
A field class that validates a list of objects.
+
Signature: ListField(child)
+
+
child - A field instance that should be used for validating the objects in the list.
+
+
For example, to validate a list of integers you might use something like the following:
The HiddenField 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.
+
For further examples on HiddenField see the validators documentation.
+
ModelField
+
A generic field that can be tied to any arbitrary model field. The ModelField 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.
+
This field is used by ModelSerializer to correspond to custom model field classes.
The ModelField class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a ModelField, it must be passed a field that is attached to an instantiated model. For example: ModelField(model_field=MyModel()._meta.get_field('custom_field'))
+
SerializerMethodField
+
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.
method-name - The name of the method on the serializer to be called. If not included this defaults to get_<field_name>.
+
+
The serializer method referred to by the method_name argument should accept a single argument (in addition to self), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
+
from django.contrib.auth.models import User
+from django.utils.timezone import now
+from rest_framework import serializers
+
+class UserSerializer(serializers.ModelSerializer):
+ days_since_joined = serializers.SerializerMethodField()
+
+ class Meta:
+ model = User
+
+ def get_days_since_joined(self, obj):
+ return (now() - obj.date_joined).days
+
Custom fields
-
If you want to create a custom field, you'll probably want to override either one or both of the .to_native() and .from_native() 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.
-
The .to_native() method is called to convert the initial datatype into a primitive, serializable datatype. The from_native() method is called to restore a primitive datatype into its initial representation.
+
If you want to create a custom field, you'll need to subclass Field and then override either one or both of the .to_representation() and .to_internal_value() 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, date/time/datetime or None. 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.
+
The .to_representation() method is called to convert the initial datatype into a primitive, serializable datatype.
+
The to_internal_value() method is called to restore a primitive datatype into its internal python representation.
+
Note that the WritableField class that was present in version 2.x no longer exists. You should subclass Field and override to_internal_value() if the field supports data input.
Examples
Let's look at an example of serializing a class that represents an RGB color value:
class Color(object):
@@ -719,22 +864,27 @@ Django's regular
-
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 .field_to_native() and/or .field_from_native().
+
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 .get_attribute() and/or .get_value().
As an example, let's create a field that can be used represent the class name of the object being serialized:
class ClassNameField(serializers.Field):
- def field_to_native(self, obj, field_name):
+ def get_attribute(self, obj):
+ # We pass the object instance onto `to_representation`,
+ # not just the field attribute.
+ return obj
+
+ def to_representation(self, obj):
"""
Serialize the object's class name.
"""
@@ -764,7 +914,7 @@ class ColourField(serializers.WritableField):
diff --git a/api-guide/filtering/index.html b/api-guide/filtering/index.html
index d7b5b88c4..654d7b054 100644
--- a/api-guide/filtering/index.html
+++ b/api-guide/filtering/index.html
@@ -164,6 +164,10 @@
Serializer relations
+
Note: This is the documentation for the version 3.0 of REST framework. Documentation for version 2.4 is also available.
+
+
Generic views
Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.
One of the key benefits of class based views is the way they allow you to compose bits of reusable behaviour. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
+
One of the key benefits of class based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.
If the generic views don't suit the needs of your API, you can drop down to using the regular APIView class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.
Examples
@@ -618,22 +629,23 @@ class UserList(generics.ListCreateAPIView):
return 20
return 100
-
Save / deletion hooks:
-
The following methods are provided as placeholder interfaces. They contain empty implementations and are not called directly by GenericAPIView, but they are overridden and used by some of the mixin classes.
+
Save and deletion hooks:
+
The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.
-
pre_save(self, obj) - A hook that is called before saving an object.
-
post_save(self, obj, created=False) - A hook that is called after saving an object.
-
pre_delete(self, obj) - A hook that is called before deleting an object.
-
post_delete(self, obj) - A hook that is called after deleting an object.
+
perform_create(self, serializer) - Called by CreateModelMixin when saving a new object instance.
+
perform_update(self, serializer) - Called by UpdateModelMixin when saving an existing object instance.
+
perform_destroy(self, instance) - Called by DestroyModelMixin when deleting an object instance.
-
The pre_save method in particular is a useful hook for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.
-
def pre_save(self, obj):
- """
- Set the object's owner, based on the incoming request.
- """
- obj.owner = self.request.user
+
These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.
Remember that the pre_save() method is not called by GenericAPIView itself, but it is called by create() and update() methods on the CreateModelMixin and UpdateModelMixin classes.
+
These override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update.
Note: These methods replace the old-style version 2.x pre_save, post_save, pre_delete and post_delete methods, which are no longer available.
Other methods:
You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using GenericAPIView.
Using custom mixins is a good option if you have custom behavior that needs to be used
+
Using custom mixins is a good option if you have custom behavior that needs to be used.
Creating custom base classes
If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example:
class BaseRetrieveView(MultipleFieldLookupMixin,
@@ -765,7 +777,7 @@ class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,
diff --git a/api-guide/pagination/index.html b/api-guide/pagination/index.html
index 28f278963..769a0b9a1 100644
--- a/api-guide/pagination/index.html
+++ b/api-guide/pagination/index.html
@@ -164,6 +164,10 @@
Serializer relations
+
@@ -449,7 +457,7 @@ sending more complex data than simple forms
REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.
How the parser is determined
-
The set of valid parsers for a view is always defined as a list of classes. When either request.DATA or request.FILES is accessed, REST framework will examine the Content-Type header on the incoming request, and determine which parser to use to parse the request content.
+
The set of valid parsers for a view is always defined as a list of classes. When request.data is accessed, REST framework will examine the Content-Type header on the incoming request, and determine which parser to use to parse the request content.
Note: When developing client applications always remember to make sure you're setting the Content-Type header when sending data in an HTTP request.
If you don't set the content type, most clients will default to using 'application/x-www-form-urlencoded', which may not be what you wanted.
Parses HTML form content. request.DATA will be populated with a QueryDict of data, request.FILES will be populated with an empty QueryDict of data.
+
Parses HTML form content. request.data will be populated with a QueryDict of data.
You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data.
.media_type: application/x-www-form-urlencoded
MultiPartParser
-
Parses multipart HTML form content, which supports file uploads. Both request.DATA and request.FILES will be populated with a QueryDict.
+
Parses multipart HTML form content, which supports file uploads. Both request.data will be populated with a QueryDict.
You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data.
.media_type: multipart/form-data
FileUploadParser
-
Parses raw file upload content. The request.DATA property will be an empty QueryDict, and request.FILES will be a dictionary with a single key 'file' containing the uploaded file.
+
Parses raw file upload content. The request.data property will be a dictionary with a single key 'file' containing the uploaded file.
If the view used with FileUploadParser is called with a filename URL keyword argument, then that argument will be used as the filename. If it is called without a filename URL keyword argument, then the client must set the filename in the Content-Disposition HTTP header. For example Content-Disposition: attachment; filename=upload.jpg.
To implement a custom parser, you should override BaseParser, set the .media_type property, and implement the .parse(self, stream, media_type, parser_context) method.
-
The method should return the data that will be used to populate the request.DATA property.
+
The method should return the data that will be used to populate the request.data property.
The arguments passed to .parse() are:
stream
A stream-like object representing the body of the request.
Note: This is the documentation for the version 3.0 of REST framework. Documentation for version 2.4 is also available.
+
+
Serializer relations
Bad programmers worry about the code.
Good programmers worry about data structures and their relationships.
@@ -462,6 +477,17 @@ Good programmers worry about data structures and their relationships.
Note: The relational fields are declared in relations.py, but by convention you should import them from the serializers module, using from rest_framework import serializers and refer to fields as serializers.<FieldName>.
+
Inspecting automatically generated relationships.
+
When using the ModelSerializer class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style.
+
To do so, open the Django shell, using python manage.py shell, then import the serializer class, instantiate it, and print the object representation…
+
>>> 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)
+ owner = PrimaryKeyRelatedField(queryset=User.objects.all())
+
API Reference
In order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album.
class Album(models.Model):
@@ -481,11 +507,11 @@ class Track(models.Model):
def __unicode__(self):
return '%d: %s' % (self.order, self.title)
-
RelatedField
-
RelatedField may be used to represent the target of the relationship using its __unicode__ method.
+
StringRelatedField
+
StringRelatedField may be used to represent the target of the relationship using its __unicode__ method.
For example, the following serializer.
class AlbumSerializer(serializers.ModelSerializer):
- tracks = serializers.RelatedField(many=True)
+ tracks = serializers.StringRelatedField(many=True)
class Meta:
model = Album
@@ -533,16 +559,19 @@ class Track(models.Model):
By default this field is read-write, although you can change this behavior using the read_only flag.
Arguments:
+
queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True.
many - If applied to a to-many relationship, you should set this argument to True.
-
required - If set to False, the field will accept values of None or the empty-string for nullable relationships.
-
queryset - By default ModelSerializer classes will use the default queryset for the relationship. Serializer classes must either set a queryset explicitly, or set read_only=True.
+
allow_null - If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False.
HyperlinkedRelatedField
HyperlinkedRelatedField may be used to represent the target of the relationship using a hyperlink.
For example, the following serializer:
class AlbumSerializer(serializers.ModelSerializer):
- tracks = serializers.HyperlinkedRelatedField(many=True, read_only=True,
- view_name='track-detail')
+ tracks = serializers.HyperlinkedRelatedField(
+ many=True,
+ read_only=True,
+ view_name='track-detail'
+ )
class Meta:
model = Album
@@ -563,19 +592,23 @@ class Track(models.Model):
By default this field is read-write, although you can change this behavior using the read_only flag.
Arguments:
-
view_name - The view name that should be used as the target of the relationship. If you're using the standard router classes this wil be a string with the format <modelname>-detail. required.
+
view_name - The view name that should be used as the target of the relationship. If you're using the standard router classes this will be a string with the format <modelname>-detail. required.
+
queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True.
many - If applied to a to-many relationship, you should set this argument to True.
-
required - If set to False, the field will accept values of None or the empty-string for nullable relationships.
-
queryset - By default ModelSerializer classes will use the default queryset for the relationship. Serializer classes must either set a queryset explicitly, or set read_only=True.
+
allow_null - If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False.
lookup_field - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is 'pk'.
+
lookup_url_kwarg - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as lookup_field.
format - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the format argument.
SlugRelatedField
SlugRelatedField may be used to represent the target of the relationship using a field on the target.
For example, the following serializer:
class AlbumSerializer(serializers.ModelSerializer):
- tracks = serializers.SlugRelatedField(many=True, read_only=True,
- slug_field='title')
+ tracks = serializers.SlugRelatedField(
+ many=True,
+ read_only=True,
+ slug_field='title'
+ )
class Meta:
model = Album
@@ -598,9 +631,9 @@ class Track(models.Model):
Arguments:
slug_field - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, username. required
+
queryset - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set read_only=True.
many - If applied to a to-many relationship, you should set this argument to True.
-
required - If set to False, the field will accept values of None or the empty-string for nullable relationships.
-
queryset - By default ModelSerializer classes will use the default queryset for the relationship. Serializer classes must either set a queryset explicitly, or set read_only=True.
+
allow_null - If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False.
HyperlinkedIdentityField
This field can be applied as an identity relationship, such as the 'url' field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
@@ -637,7 +670,7 @@ class Track(models.Model):
fields = ('order', 'title')
class AlbumSerializer(serializers.ModelSerializer):
- tracks = TrackSerializer(many=True)
+ tracks = TrackSerializer(many=True, read_only=True)
class Meta:
model = Album
@@ -656,14 +689,14 @@ class AlbumSerializer(serializers.ModelSerializer):
}
Custom relational fields
-
To implement a custom relational field, you should override RelatedField, and implement the .to_native(self, value) method. This method takes the target of the field as the value argument, and should return the representation that should be used to serialize the target.
-
If you want to implement a read-write relational field, you must also implement the .from_native(self, data) method, and add read_only = False to the class definition.
+
To implement a custom relational field, you should override RelatedField, and implement the .to_representation(self, value) method. This method takes the target of the field as the value argument, and should return the representation that should be used to serialize the target. The value argument will typically be a model instance.
+
If you want to implement a read-write relational field, you must also implement the .to_internal_value(self, data) method.
Example
For, example, we could define a relational field, to serialize a track to a custom string representation, using its ordering, title, and duration.
The queryset argument is only ever required for writable relationship field, in which case it is used for performing the model instance lookup, that maps from the primitive user input, into a model instance.
+
In version 2.x a serializer class could sometimes automatically determine the queryset argument if a ModelSerializer class was being used.
+
This behavior is now replaced with always using an explicit queryset argument for writable relational fields.
+
Doing so reduces the amount of hidden 'magic' that ModelSerializer provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the ModelSerializer shortcut, or using fully explicit Serializer classes.
Reverse relations
Note that reverse relationships are not automatically included by the ModelSerializer and HyperlinkedModelSerializer classes. To include a reverse relationship, you must explicitly add it to the fields list. For example:
class AlbumSerializer(serializers.ModelSerializer):
@@ -744,7 +782,7 @@ class Note(models.Model):
A custom field to use for the `tagged_object` generic relationship.
"""
- def to_native(self, value):
+ def to_representation(self, value):
"""
Serialize tagged objects to a simple textual representation.
"""
@@ -754,8 +792,8 @@ class Note(models.Model):
return 'Note: ' + value.text
raise Exception('Unexpected type of tagged object')
-
If you need the target of the relationship to have a nested representation, you can use the required serializers inside the .to_native() method:
-
def to_native(self, value):
+
If you need the target of the relationship to have a nested representation, you can use the required serializers inside the .to_native() method:
+
def to_representation(self, value):
"""
Serialize bookmark instances using a bookmark serializer,
and note instances using a note serializer.
@@ -800,20 +838,6 @@ attributes are not configured to correctly match the URL conf.
return queryset.get(account=account, slug=slug)
-
Deprecated APIs
-
The following classes have been deprecated, in favor of the many=<bool> syntax.
-They continue to function, but their usage will raise a PendingDeprecationWarning, which is silent by default.
-
-
ManyRelatedField
-
ManyPrimaryKeyRelatedField
-
ManyHyperlinkedRelatedField
-
ManySlugRelatedField
-
-
The null=<bool> flag has been deprecated in favor of the required=<bool> flag. It will continue to function, but will raise a PendingDeprecationWarning.
-
In the 2.3 release, these warnings will be escalated to a DeprecationWarning, which is loud by default.
-In the 2.4 release, these parts of the API will be removed entirely.
The following third party packages are also available.
DRF Nested Routers
@@ -832,7 +856,7 @@ In the 2.4 release, these parts of the API will be removed entirely.
diff --git a/api-guide/renderers/index.html b/api-guide/renderers/index.html
index bee33198a..9034cd115 100644
--- a/api-guide/renderers/index.html
+++ b/api-guide/renderers/index.html
@@ -164,6 +164,10 @@
Serializer relations
+
@@ -799,7 +807,7 @@ In this case you can underspecify the media types it should respond to, by using
diff --git a/api-guide/requests/index.html b/api-guide/requests/index.html
index a074e516f..11781510a 100644
--- a/api-guide/requests/index.html
+++ b/api-guide/requests/index.html
@@ -164,6 +164,10 @@
Serializer relations
+
REST framework's Request objects provide flexible request parsing that allows you to treat requests with JSON data or other media types in the same way that you would normally deal with form data.
-
.DATA
-
request.DATA returns the parsed content of the request body. This is similar to the standard request.POST attribute except that:
+
.data
+
request.data returns the parsed content of the request body. This is similar to the standard request.POST and request.FILES attributes except that:
+
It includes all parsed content, including file and non-file inputs.
It supports parsing the content of HTTP methods other than POST, meaning that you can access the content of PUT and PATCH requests.
It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data.
request.FILES returns any uploaded files that may be present in the content of the request body. This is the same as the standard HttpRequest behavior, except that the same flexible request parsing is used for request.DATA.
request.QUERY_PARAMS is a more correctly named synonym for request.GET.
-
For clarity inside your code, we recommend using request.QUERY_PARAMS instead of the usual request.GET, as any HTTP method type may include query parameters.
+
.query_params
+
request.query_params is a more correctly named synonym for request.GET.
+
For clarity inside your code, we recommend using request.query_params instead of the Django's standard request.GET. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just GET requests.
+
.DATA and .FILES
+
The old-style version 2.x request.data and request.FILES attributes are still available, but are now pending deprecation in favor of the unified request.data attribute.
+
.QUERY_PARAMS
+
The old-style version 2.x request.QUERY_PARAMS attribute is still available, but is now pending deprecation in favor of the more pythonic request.query_params.
.parsers
The APIView class or @api_view decorator will ensure that this property is automatically set to a list of Parser instances, based on the parser_classes set on the view or based on the DEFAULT_PARSER_CLASSES setting.
You won't typically need to access this property.
-
Note: If a client sends malformed content, then accessing request.DATA or request.FILES may raise a ParseError. By default REST framework's APIView class or @api_view decorator will catch the error and return a 400 Bad Request response.
+
Note: If a client sends malformed content, then accessing request.data may raise a ParseError. By default REST framework's APIView class or @api_view decorator will catch the error and return a 400 Bad Request response.
If a client sends a request with a content-type that cannot be parsed then a UnsupportedMediaType exception will be raised, which by default will be caught and return a 415 Unsupported Media Type response.
Note: This is the documentation for the version 3.0 of REST framework. Documentation for version 2.4 is also available.
+
+
Serializers
Expanding the usefulness of the serializers is something that we would
like to address. However, it's not a trivial problem, and it
@@ -488,7 +551,7 @@ will take some serious design work.
Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
-
REST framework's serializers work very similarly to Django's Form and ModelForm classes. It provides a Serializer class which gives you a powerful, generic way to control the output of your responses, as well as a ModelSerializer class which provides a useful shortcut for creating serializers that deal with model instances and querysets.
+
The serializers in REST framework work very similarly to Django's Form and ModelForm classes. We provide a Serializer class which gives you a powerful, generic way to control the output of your responses, as well as a ModelSerializer class which provides a useful shortcut for creating serializers that deal with model instances and querysets.
Declaring Serializers
Let's start by creating a simple object we can use for example purposes:
class Comment(object):
@@ -499,7 +562,7 @@ will take some serious design work.
comment = Comment(email='leila@example.com', content='foo bar')
-
We'll declare a serializer that we can use to serialize and deserialize Comment objects.
+
We'll declare a serializer that we can use to serialize and deserialize data that corresponds to Comment objects.
Declaring a serializer looks very similar to declaring a form:
from rest_framework import serializers
@@ -507,23 +570,9 @@ class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
-
- def restore_object(self, attrs, instance=None):
- """
- Given a dictionary of deserialized field values, either update
- an existing model instance, or create a new model instance.
- """
- if instance is not None:
- instance.email = attrs.get('email', instance.email)
- instance.content = attrs.get('content', instance.content)
- instance.created = attrs.get('created', instance.created)
- return instance
- return Comment(**attrs)
-
The first part of serializer class defines the fields that get serialized/deserialized. The restore_object method defines how fully fledged instances get created when deserializing data.
-
The restore_object 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.
Serializing objects
-
We can now use CommentSerializer to serialize a comment, or list of comments. Again, using the Serializer class looks a lot like using a Form class.
+
We can now use CommentSerializer to serialize a comment, or list of comments. Again, using the Serializer class looks a lot like using a Form class.
Sometimes when serializing objects, you may not want to represent everything exactly the way it is in your model.
-
If you need to customize the serialized value of a particular field, you can do this by creating a transform_<fieldname> method. For example if you needed to render some markdown from a text field:
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 .create() and update() methods. For example:
By default, serializers must be passed values for all required fields or they will throw validation errors. You can use the partial argument in order to allow partial updates.
-
serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True) # Update `comment` with partial data
+
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 Comment was a Django model, the methods might look like this:
Now when deserializing data, we can call .save() to return an object instance, based on the validated data.
+
comment = serializer.save()
+
+
Calling .save() will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class:
+
# .save() will create a new instance.
+serializer = CommentSerializer(data=data)
+
+# .save() will update the existing `comment` instance.
+serializer = CommentSerializer(comment, data=data)
+
+
Both the .create() and .update() methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class.
+
Passing additional attributes to .save()
+
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.
+
You can do so by including additional keyword arguments when calling .save(). For example:
+
serializer.save(owner=request.user)
+
+
Any additional keyword arguments will be included in the validated_data argument when .create() or .update() are called.
+
Overriding .save() directly.
+
In some cases the .create() and .update() 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.
+
In these cases you might instead choose to override .save() directly, as being more readable and meaningful.
Note that in the case above we're now having to access the serializer .validated_data property directly.
Validation
-
When deserializing data, you always need to call is_valid() before attempting to access the deserialized object. If any validation errors occur, the .errors property will contain a dictionary representing the resulting error messages. For example:
+
When deserializing data, you always need to call is_valid() before attempting to access the validated data, or save an object instance. If any validation errors occur, the .errors property will contain a dictionary representing the resulting error messages. For example:
serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})
serializer.is_valid()
# False
serializer.errors
# {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']}
-
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 non_field_errors key may also be present, and will list any general validation errors.
+
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 non_field_errors key may also be present, and will list any general validation errors. The name of the non_field_errors key may be customized using the NON_FIELD_ERRORS_KEY REST framework setting.
When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.
+
Raising an exception on invalid data
+
The .is_valid() method takes an optional raise_exception flag that will cause it to raise a serializers.ValidationError exception if there are validation errors.
+
These exceptions are automatically dealt with by the default exception handler that REST framework provides, and will return HTTP 400 Bad Request responses by default.
+
# Return a 400 response if the data was invalid.
+serializer.is_valid(raise_exception=True)
+
Field-level validation
-
You can specify custom field-level validation by adding .validate_<fieldname> methods to your Serializer subclass. These are analogous to .clean_<fieldname> methods on Django forms, but accept slightly different arguments.
-
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 source argument to the field, if one was provided).
-
Your validate_<fieldname> methods should either just return the attrs dictionary or raise a ValidationError. For example:
+
You can specify custom field-level validation by adding .validate_<field_name> methods to your Serializer subclass. These are similar to the .clean_<field_name> methods on Django forms.
+
These methods take a single argument, which is the field value that requires validation.
+
Your validate_<field_name> methods should return the validated value or raise a serializers.ValidationError. For example:
from rest_framework import serializers
class BlogPostSerializer(serializers.Serializer):
title = serializers.CharField(max_length=100)
content = serializers.CharField()
- def validate_title(self, attrs, source):
+ def validate_title(self, value):
"""
Check that the blog post is about Django.
"""
- value = attrs[source]
- if "django" not in value.lower():
+ if 'django' not in value.lower():
raise serializers.ValidationError("Blog post is not about Django")
- return attrs
+ return value
Object-level validation
-
To do any other validation that requires access to multiple fields, add a method called .validate() to your Serializer subclass. This method takes a single argument, which is the attrs dictionary. It should raise a ValidationError if necessary, or just return attrs. For example:
+
To do any other validation that requires access to multiple fields, add a method called .validate() to your Serializer subclass. This method takes a single argument, which is a dictionary of field values. It should raise a ValidationError if necessary, or just return the validated values. For example:
from rest_framework import serializers
class EventSerializer(serializers.Serializer):
@@ -606,21 +700,43 @@ class EventSerializer(serializers.Serializer):
start = serializers.DateTimeField()
finish = serializers.DateTimeField()
- def validate(self, attrs):
+ def validate(self, data):
"""
Check that the start is before the stop.
"""
- if attrs['start'] > attrs['finish']:
+ if data['start'] > data['finish']:
raise serializers.ValidationError("finish must occur after start")
- return attrs
+ return data
-
Saving object state
-
To save the deserialized objects created by a serializer, call the .save() method:
-
if serializer.is_valid():
- serializer.save()
+
Validators
+
Individual fields on a serializer can include validators, by declaring them on the field instance, for example:
+
def multiple_of_ten(value):
+ if value % 10 != 0:
+ raise serializers.ValidationError('Not a multiple of ten')
+
+class GameRecord(serializers.Serializer):
+ score = IntegerField(validators=[multiple_of_ten])
+ ...
+
+
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 Meta class, like so:
+
class EventSerializer(serializers.Serializer):
+ name = serializers.CharField()
+ room_number = serializers.IntegerField(choices=[101, 102, 103, 201])
+ date = serializers.DateField()
+
+ class Meta:
+ # Each room only has one event per day.
+ validators = UniqueTogetherValidator(
+ queryset=Event.objects.all(),
+ fields=['room_number', 'date']
+ )
+
By default, serializers must be passed values for all required fields or they will raise validation errors. You can use the partial argument in order to allow partial updates.
+
# Update `comment` with partial data
+serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)
-
The default behavior of the method is to simply call .save() on the deserialized object instance. You can override the default save behaviour by overriding the .save_object(obj) method on the serializer class.
-
The generic views provided by REST framework call the .save() method when updating or creating entities.
Dealing with nested objects
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.
The Serializer class is itself a type of Field, and can be used to represent relationships where one object type is nested inside another.
@@ -646,13 +762,92 @@ class CommentSerializer(serializers.Serializer):
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
-
Validation of nested objects will work the same as before. Errors with nested objects will be nested under the field name of the nested object.
+
Writable nested representations
+
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.
serializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'})
serializer.is_valid()
# False
serializer.errors
# {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']}
+
Similarly, the .validated_data property will include nested data structures.
+
Writing .create() methods for nested representations
+
If you're supporting writable nested representations you'll need to write .create() or .update() methods that handle saving multiple objects.
+
The following example demonstrates how you might handle creating a user with a nested profile object.
+
class UserSerializer(serializers.ModelSerializer):
+ profile = ProfileSerializer()
+
+ class Meta:
+ model = User
+ fields = ('username', 'email', 'profile')
+
+ def create(self, validated_data):
+ profile_data = validated_data.pop('profile')
+ user = User.objects.create(**validated_data)
+ Profile.objects.create(user=user, **profile_data)
+ return user
+
+
Writing .update() methods for nested representations
+
For updates you'll want to think carefully about how to handle updates to relationships. For example if the data for the relationship is None, or not provided, which of the following should occur?
+
+
Set the relationship to NULL in the database.
+
Delete the associated instance.
+
Ignore the data and leave the instance as it is.
+
Raise a validation error.
+
+
Here's an example for an update() method on our previous UserSerializer class.
+
def update(self, instance, validated_data):
+ profile_data = validated_data.pop('profile')
+ # Unless the application properly enforces that this field is
+ # always set, the follow could raise a `DoesNotExist`, which
+ # would need to be handled.
+ profile = instance.profile
+
+ user.username = validated_data.get('username', instance.username)
+ user.email = validated_data.get('email', instance.email)
+ user.save()
+
+ profile.is_premium_member = profile_data.get(
+ 'is_premium_member',
+ profile.is_premium_member
+ )
+ profile.has_support_contract = profile_data.get(
+ 'has_support_contract',
+ profile.has_support_contract
+ )
+ profile.save()
+
+ return user
+
+
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 ModelSerializer.create() and .update() methods do not include support for writable nested representations.
+
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.
+
Handling saving related instances in model manager classes
+
An alternative to saving multiple related instances in the serializer is to write custom model manager classes handle creating the correct instances.
+
For example, suppose we wanted to ensure that User instances and Profile instances are always created together as a pair. We might write a custom manager class that looks something like this:
This manager class now more nicely encapsulates that user instances and profile instances are always created at the same time. Our .create() method on the serializer class can now be re-written to use the new manager method.
To deserialize a list of object data, and create multiple object instances in a single pass, you should also set the many=True flag, and pass a list of data to be deserialized.
-
This allows you to write views that create multiple items when a POST request is made.
-
For example:
-
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
-
-
Deserializing multiple objects for update
-
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.
-
This allows you to write views that update or create multiple items when a PUT request is made.
-
# 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 = BookSerializer(queryset, data=data, many=True)
-serializer.is_valid()
-# True
-serializer.save() # `.save()` will be called on each updated or newly created instance.
-
-
By default bulk updates will be limited to updating instances that already exist in the provided queryset.
-
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 allow_add_remove=True to the serializer.
-
serializer = BookSerializer(queryset, data=data, many=True, allow_add_remove=True)
-serializer.is_valid()
-# True
-serializer.save() # `.save()` will be called on updated or newly created instances.
- # `.delete()` will be called on any other items in the `queryset`.
-
-
Passing allow_add_remove=True ensures that any update operations will completely overwrite the existing queryset, rather than simply updating existing objects.
-
How identity is determined when performing bulk updates
-
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.
-
By default the serializer class will use the id key on the incoming data to determine the canonical identity of an object. If you need to change this behavior you should override the get_identity method on the Serializer class. For example:
-
class AccountSerializer(serializers.Serializer):
- slug = serializers.CharField(max_length=100)
- created = serializers.DateTimeField()
- ... # Various other fields
-
- def get_identity(self, data):
- """
- This hook is required for bulk update.
- 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
-
-
To map the incoming data items to their corresponding object instances, the .get_identity() method will be called both against the incoming data, and against the serialized representation of the existing objects.
+
Deserializing multiple objects
+
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 ListSerializer documentation below.
Including extra context
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.
You can provide arbitrary additional context by passing a context argument when instantiating the serializer. For example:
@@ -732,20 +870,35 @@ serializer.save() # `.save()` will be called on updated or newly created instan
serializer.data
# {'id': 6, 'owner': u'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}
-
The context dictionary can be used within any serializer field logic, such as a custom .to_native() method, by accessing the self.context attribute.
-
-
+
The context dictionary can be used within any serializer field logic, such as a custom .to_representation() method, by accessing the self.context attribute.
+
ModelSerializer
-
Often you'll want serializer classes that map closely to model definitions.
-The ModelSerializer class lets you automatically create a Serializer class with fields that correspond to the Model fields.
+
Often you'll want serializer classes that map closely to Django model definitions.
+
The ModelSerializer class provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields.
+
The ModelSerializer class is the same as a regular Serializer class, except that:
+
+
It will automatically generate a set of fields for you, based on the model.
+
It will automatically generate validators for the serializer, such as unique_together validators.
+
It includes simple default implementations of .create() and .update().
+
+
Declaring a ModelSerializer looks like this:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
-
By default, all the model fields on the class will be mapped to corresponding serializer fields.
-
Any relationships such as foreign keys on the model will be mapped to PrimaryKeyRelatedField. Other models fields will be mapped to a corresponding serializer field.
-
-
Note: When validation is applied to a ModelSerializer, 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 blank=True on the model field, as well as setting required=False on the serializer field.
-
+
By default, all the model fields on the class will be mapped to a corresponding serializer fields.
+
Any relationships such as foreign keys on the model will be mapped to PrimaryKeyRelatedField. Reverse relationships are not included by default unless explicitly included as described below.
+
Inspecting a ModelSerializer
+
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 ModelSerializers where you want to determine what set of fields and validators are being automatically created for you.
+
To do so, open the Django shell, using python manage.py shell, then import the serializer class, instantiate it, and print the object representation…
+
>>> 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)
+ owner = PrimaryKeyRelatedField(queryset=User.objects.all())
+
Specifying which fields should be included
If you only want a subset of the default fields to be used in a model serializer, you can do so using fields or exclude options, just as you would with a ModelForm.
For example:
@@ -754,6 +907,8 @@ The ModelSerializer class lets you automatically create a Serialize
model = Account
fields = ('id', 'account_name', 'users', 'created')
+
The names in the fields option will normally map to model fields on the model class.
+
Alternatively names in the fields options can map to properties or methods which take no arguments that exist on the model class.
Specifying nested serialization
The default ModelSerializer uses primary keys for relationships, but you can also easily generate nested representations using the depth option:
class AccountSerializer(serializers.ModelSerializer):
@@ -764,32 +919,6 @@ The ModelSerializer class lets you automatically create a Serialize
The depth option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.
If you want to customize the way the serialization is done (e.g. using allow_add_remove) you'll need to define the field yourself.
-
Specifying which fields should be read-only
-
You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the read_only=True attribute, you may use the read_only_fields Meta option, like so:
-
class AccountSerializer(serializers.ModelSerializer):
- class Meta:
- model = Account
- fields = ('id', 'account_name', 'users', 'created')
- read_only_fields = ('account_name',)
-
-
Model fields which have editable=False set, and AutoField fields will be set to read-only by default, and do not need to be added to the read_only_fields option.
-
Specifying which fields should be write-only
-
You may wish to specify multiple fields as write-only. Instead of adding each field explicitly with the write_only=True attribute, you may use the write_only_fields Meta option, like so:
-
class CreateUserSerializer(serializers.ModelSerializer):
- class Meta:
- model = User
- fields = ('email', 'username', 'password')
- write_only_fields = ('password',) # Note: Password field is write-only
-
- def restore_object(self, attrs, instance=None):
- """
- Instantiate a new User instance.
- """
- assert instance is None, 'Cannot update users with CreateUserSerializer'
- user = User(email=attrs['email'], username=attrs['username'])
- user.set_password(attrs['password'])
- return user
-
Specifying fields explicitly
You can add extra fields to a ModelSerializer or override the default fields by declaring fields on the class, just as you would for a Serializer class.
class AccountSerializer(serializers.ModelSerializer):
@@ -800,12 +929,40 @@ The ModelSerializer class lets you automatically create a Serialize
model = Account
Extra fields can correspond to any property or callable on the model.
+
Specifying which fields should be read-only
+
You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the read_only=True attribute, you may use the shortcut Meta option, read_only_fields.
+
This option should be a list or tuple of field names, and is declared as follows:
+
class AccountSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = Account
+ fields = ('id', 'account_name', 'users', 'created')
+ read_only_fields = ('account_name',)
+
+
Model fields which have editable=False set, and AutoField fields will be set to read-only by default, and do not need to be added to the read_only_fields option.
+
Specifying additional keyword arguments for fields.
+
There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the extra_kwargs option. Similarly to read_only_fields this means you do not need to explicitly declare the field on the serializer.
+
This option is a dictionary, mapping field names to a dictionary of keyword arguments. For example:
+
class CreateUserSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = User
+ fields = ('email', 'username', 'password')
+ extra_kwargs = {'password': {'write_only': True}}
+
+ def create(self, validated_data):
+ user = User(
+ email=validated_data['email'],
+ username=validated_data['username']
+ )
+ user.set_password(validated_data['password'])
+ user.save()
+ return user
+
Relational fields
When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for ModelSerializer is to use the primary keys of the related instances.
Alternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation.
The inner Meta class on serializers is not inherited from parent classes by default. This is the same behaviour as with Django's Model and ModelForm classes. If you want the Meta class to inherit from a parent class you must do so explicitly. For example:
+
The inner Meta class on serializers is not inherited from parent classes by default. This is the same behavior as with Django's Model and ModelForm classes. If you want the Meta class to inherit from a parent class you must do so explicitly. For example:
class AccountSerializer(MyBaseSerializer):
class Meta(MyBaseSerializer.Meta):
model = Account
@@ -825,19 +982,21 @@ The ModelSerializer class lets you automatically create a Serialize
How hyperlinked views are determined
There needs to be a way of determining which views should be used for hyperlinking to model instances.
By default hyperlinks are expected to correspond to a view name that matches the style '{model_name}-detail', and looks up the instance by a pk keyword argument.
-
You can change the field that is used for object lookups by setting the lookup_field 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:
+
You can override a URL field view name and lookup field by using either, or both of, the view_name and lookup_field options in the extra_field_kwargs setting, like so:
Note that the lookup_field will be used as the default on all hyperlinked fields, including both the URL identity, and any hyperlinked relationships.
-
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:
+
Alternatively you can set the fields on the serializer explicitly. For example:
class AccountSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(
- view_name='account_detail',
- lookup_field='account_name'
+ view_name='accounts',
+ lookup_field='slug'
)
users = serializers.HyperlinkedRelatedField(
view_name='user-detail',
@@ -850,28 +1009,221 @@ The ModelSerializer class lets you automatically create a Serialize
model = Account
fields = ('url', 'account_name', 'users', 'created')
-
Overriding the URL field behavior
+
+
Tip: Properly matching together hyperlinked representations and your URL conf can sometimes be a bit fiddly. Printing the repr of a HyperlinkedModelSerializer instance is a particularly useful way to inspect exactly which view names and lookup fields the relationships are expected to map too.
+
+
Changing the URL field name
The name of the URL field defaults to 'url'. You can override this globally, by using the URL_FIELD_NAME setting.
-
You can also override this on a per-serializer basis by using the url_field_name option on the serializer, like so:
-
class AccountSerializer(serializers.HyperlinkedModelSerializer):
+
+
ListSerializer
+
The ListSerializer class provides the behavior for serializing and validating multiple objects at once. You won't typically need to use ListSerializer directly, but should instead simply pass many=True when instantiating a serializer.
+
When a serializer is instantiated and many=True is passed, a ListSerializer instance will be created. The serializer class then becomes a child of the parent ListSerializer
+
There are a few use cases when you might want to customize the ListSerializer behavior. For example:
+
+
You want to provide particular validation of the lists, such as always ensuring that there is at least one element in a list.
+
You want to customize the create or update behavior of multiple objects.
+
+
For these cases you can modify the class that is used when many=True is passed, by using the list_serializer_class option on the serializer Meta class.
+
For example:
+
class CustomListSerializer(serializers.ListSerializer):
+ ...
+
+class CustomSerializer(serializers.Serializer):
+ ...
class Meta:
- model = Account
- fields = ('account_url', 'account_name', 'users', 'created')
- url_field_name = 'account_url'
+ list_serializer_class = CustomListSerializer
-
Note: The generic view implementations normally generate a Location header in response to successful POST requests. Serializers using url_field_name 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 get_success_headers() method.
-
You can also override the URL field's view name and lookup field without overriding the field explicitly, by using the view_name and lookup_field options, like so:
-
class AccountSerializer(serializers.HyperlinkedModelSerializer):
+
Customizing multiple create
+
The default implementation for multiple object creation is to simply call .create() for each item in the list. If you want to customize this behavior, you'll need to customize the .create() method on ListSerializer class that is used when many=True is passed.
+
For example:
+
class BookListSerializer(serializers.ListSerializer):
+ def create(self, validated_data):
+ books = [Book(**item) for item in validated_data]
+ return Book.objects.bulk_create(books)
+
+class BookSerializer(serializers.Serializer):
+ ...
class Meta:
- model = Account
- fields = ('account_url', 'account_name', 'users', 'created')
- view_name = 'account_detail'
- lookup_field='account_name'
+ list_serializer_class = BookListSerializer
+
+
Customizing multiple update
+
By default the ListSerializer class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous.
+
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:
+
+
How do you determine which instance should be updated for each item in the list of data?
+
How should insertions be handled? Are they invalid, or do they create new objects?
+
How should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid?
+
How should ordering be handled? Does changing the position of two items imply any state change or is it ignored?
+
+
Here's an example of how you might choose to implement multiple updates:
+
class BookListSerializer(serializers.ListSerializer):
+ def update(self, instance, validated_data):
+ # Maps for id->instance and id->data item.
+ 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
+
+
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 allow_add_remove behavior that was present in REST framework 2.
+
+
BaseSerializer
+
BaseSerializer class that can be used to easily support alternative serialization and deserialization styles.
+
This class implements the same basic API as the Serializer class:
+
+
.data - Returns the outgoing primitive representation.
+
.is_valid() - Deserializes and validates incoming data.
+
.validated_data - Returns the validated incoming data.
+
.errors - Returns an errors during validation.
+
.save() - Persists the validated data into an object instance.
+
+
There are four methods that can be overridden, depending on what functionality you want the serializer class to support:
+
+
.to_representation() - Override this to support serialization, for read operations.
+
.to_internal_value() - Override this to support deserialization, for write operations.
+
.create() and .update() - Overide either or both of these to support saving instances.
+
+
Because this class provides the same interface as the Serializer class, you can use it with the existing generic class based views exactly as you would for a regular Serializer or ModelSerializer.
+
The only difference you'll notice when doing so is the BaseSerializer 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.
+
Read-only BaseSerializer classes
+
To implement a read-only serializer using the BaseSerializer class, we just need to override the .to_representation() method. Let's take a look at an example using a simple Django model:
+
class HighScore(models.Model):
+ created = models.DateTimeField(auto_now_add=True)
+ player_name = models.CharField(max_length=10)
+ score = models.IntegerField()
+
+
It's simple to create a read-only serializer for converting HighScore instances into primitive data types.
To create a read-write serializer we first need to implement a .to_internal_value() method. This method returns the validated values that will be used to construct the object instance, and may raise a ValidationError if the supplied data is in an incorrect format.
+
Once you've implemented .to_internal_value(), the basic validation API will be available on the serializer, and you will be able to use .is_valid(), .validated_data and .errors.
+
If you want to also support .save() you'll need to also implement either or both of the .create() and .update() methods.
+
Here's a complete example of our previous HighScoreSerializer, that's been updated to support both read and write operations.
+
class HighScoreSerializer(serializers.BaseSerializer):
+ def to_internal_value(self, data):
+ score = data.get('score')
+ player_name = data.get('player_name')
+
+ # Perform the data validation.
+ if not score:
+ raise ValidationError({
+ 'score': 'This field is required.'
+ })
+ if not player_name:
+ raise ValidationError({
+ 'player_name': 'This field is required.'
+ })
+ if len(player_name) > 10:
+ raise ValidationError({
+ '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)
+
+
Creating new base classes
+
The BaseSerializer 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.
+
The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.
+
class ObjectSerializer(serializers.BaseSerializer):
+ """
+ A read-only serializer that coerces arbitrary complex objects
+ into primitive representations.
+ """
+ def to_representation(self, obj):
+ for attribute_name in dir(obj):
+ attribute = getattr(obj, attribute_name)
+ if attribute_name('_'):
+ # Ignore private attributes.
+ pass
+ elif hasattr(attribute, '__call__'):
+ # Ignore methods and other callables.
+ pass
+ elif isinstance(attribute, (str, int, bool, float, type(None))):
+ # Primitive types can be passed through unmodified.
+ output[attribute_name] = attribute
+ elif isinstance(attribute, list):
+ # Recursively deal with items in lists.
+ output[attribute_name] = [
+ self.to_representation(item) for item in attribute
+ ]
+ elif isinstance(attribute, dict):
+ # Recursively deal with items in dictionaries.
+ output[attribute_name] = {
+ str(key): self.to_representation(value)
+ for key, value in attribute.items()
+ }
+ else:
+ # Force anything else to its string representation.
+ output[attribute_name] = str(attribute)
Advanced serializer usage
-
You can create customized subclasses of ModelSerializer or HyperlinkedModelSerializer that use a different set of default fields.
-
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.
+
Overriding serialization and deserialization behavior
+
If you need to alter the serialization, deserialization or validation of a serializer class you can do so by overriding the .to_representation() or .to_internal_value() methods.
+
Some reasons this might be useful include...
+
+
Adding new behavior for new serializer base classes.
+
Modifying the behavior slightly for an existing class.
+
Improving serialization performance for a frequently accessed API endpoint that returns lots of data.
+
+
The signatures for these methods are as follows:
+
.to_representation(self, obj)
+
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.
+
.to_internal_value(self, data)
+
Takes the unvalidated incoming data as input and should return the validated data that will be made available as serializer.validated_data. The return value will also be passed to the .create() or .update() methods if .save() is called on the serializer class.
+
If any of the validation fails, then the method should raise a serializers.ValidationError(errors). Typically the errors argument here will be a dictionary mapping field names to error messages.
+
The data argument passed to this method will normally be the value of request.data, so the datatype it provides will depend on the parser classes you have configured for your API.
Dynamically modifying fields
Once a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the .fields attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer.
Modifying the fields 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.
@@ -890,7 +1242,7 @@ The ModelSerializer class lets you automatically create a Serialize
# Instantiate the superclass normally
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
- if fields:
+ if fields is not None:
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(self.fields.keys())
@@ -909,29 +1261,11 @@ The ModelSerializer class lets you automatically create a Serialize
>>> print UserSerializer(user, fields=('id', 'email'))
{'id': 2, 'email': 'jon@example.com'}
-
Customising the default fields
-
The field_mapping 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.
-
For more advanced customization than simply changing the default serializer class you can override various get_<field_type>_field 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 None.
-
get_pk_field
-
Signature: .get_pk_field(self, model_field)
-
Returns the field instance that should be used to represent the pk field.
Returns the field instance that should be used to represent a related field when depth is specified as being non-zero.
-
Note that the model_field argument will be None for reverse relationships. The related_model argument will be the model class for the target of the field. The to_many argument will be a boolean indicating if this is a to-one or to-many relationship.
Returns the field instance that should be used to represent a related field when depth is not specified, or when nested representations are being used and the depth reaches zero.
-
Note that the model_field argument will be None for reverse relationships. The related_model argument will be the model class for the target of the field. The to_many argument will be a boolean indicating if this is a to-one or to-many relationship.
-
get_field
-
Signature: .get_field(self, model_field)
-
Returns the field instance that should be used for non-relational, non-pk fields.
-
Example
-
The following custom model serializer could be used as a base class for model serializers that should always exclude the pk by default.
-
class NoPKModelSerializer(serializers.ModelSerializer):
- def get_pk_field(self, model_field):
- return None
-
+
Customizing the default fields
+
REST framework 2 provided an API to allow developers to override how a ModelSerializer class would automatically generate the default set of fields.
+
This API included the .get_field(), .get_pk_field() and other methods.
+
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.
+
A new interface for controlling this behavior is currently planned for REST framework 3.1.
Third party packages
The following third party packages are also available.
@@ -955,7 +1289,7 @@ The ModelSerializer class lets you automatically create a Serialize
diff --git a/api-guide/settings/index.html b/api-guide/settings/index.html
index 9591d4658..ae315e896 100644
--- a/api-guide/settings/index.html
+++ b/api-guide/settings/index.html
@@ -164,6 +164,10 @@
Serializer relations
+
Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes.
+
However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.
+
Validation in REST framework
+
Validation in Django REST framework serializers is handled a little differently to how validation works in Django's ModelForm class.
+
With ModelForm the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:
+
+
It introduces a proper separation of concerns, making your code behavior more obvious.
+
It is easy to switch between using shortcut ModelSerializer classes and using explicit Serializer classes. Any validation behavior being used for ModelSerializer is simple to replicate.
+
Printing the repr of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.
+
+
When you're using ModelSerializer all of this is handled automatically for you. If you want to drop down to using a Serializer classes instead, then you need to define the validation rules explicitly.
+
Example
+
As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint.
The interesting bit here is the reference field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field.
+
Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below.
+
+
UniqueValidator
+
This validator can be used to enforce the unique=True constraint on model fields.
+It takes a single required argument, and an optional messages argument:
+
+
querysetrequired - This is the queryset against which uniqueness should be enforced.
+
message - The error message that should be used when validation fails.
+
+
This validator should be applied to serializer fields, like so:
This validator can be used to enforce unique_together constraints on model instances.
+It has two required arguments, and a single optional messages argument:
+
+
querysetrequired - This is the queryset against which uniqueness should be enforced.
+
fieldsrequired - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class.
+
message - The error message that should be used when validation fails.
+
+
The validator should be applied to serializer classes, like so:
+
class ExampleSerializer(serializers.Serializer):
+ # ...
+ class Meta:
+ # ToDo items belong to a parent list, and have an ordering defined
+ # by the 'position' field. No two items in a given list may share
+ # the same position.
+ validators = [
+ UniqueTogetherValidator(
+ queryset=ToDoItem.objects.all(),
+ fields=('list', 'position')
+ )
+ ]
+
+
+
Note: The UniqueTogetherValidation class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with default values are an exception to this as they always supply a value even when omitted from user input.
+
+
UniqueForDateValidator
+
UniqueForMonthValidator
+
UniqueForYearValidator
+
These validators can be used to enforce the unique_for_date, unique_for_month and unique_for_year constraints on model instances. They take the following arguments:
+
+
querysetrequired - This is the queryset against which uniqueness should be enforced.
+
fieldrequired - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class.
+
date_fieldrequired - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class.
+
message - The error message that should be used when validation fails.
+
+
The validator should be applied to serializer classes, like so:
+
class ExampleSerializer(serializers.Serializer):
+ # ...
+ class Meta:
+ # Blog posts should have a slug that is unique for the current year.
+ validators = [
+ UniqueForYearValidator(
+ queryset=BlogPostItem.objects.all(),
+ field='slug',
+ date_field='published'
+ )
+ ]
+
+
The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class default=..., because the value being used for the default wouldn't be generated until after the validation has run.
+
There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using ModelSerializer you'll probably simply rely on the defaults that REST framework generates for you, but if you are using Serializer or simply want more explicit control, use on of the styles demonstrated below.
+
Using with a writable date field.
+
If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a default argument, or by setting required=True.
+
published = serializers.DateTimeField(required=True)
+
+
Using with a read-only date field.
+
If you want the date field to be visible, but not editable by the user, then set read_only=True and additionally set a default=... argument.
+
published = serializers.DateTimeField(read_only=True, default=timezone.now)
+
+
The field will not be writable to the user, but the default value will still be passed through to the validated_data.
+
Using with a hidden date field.
+
If you want the date field to be entirely hidden from the user, then use HiddenField. This field type does not accept user input, but instead always returns it's default value to the validated_data in the serializer.
+
published = serializers.HiddenField(default=timezone.now)
+
+
+
Note: The UniqueFor<Range>Validation classes always imposes an implicit constraint that the fields they are applied to are always treated as required. Fields with default values are an exception to this as they always supply a value even when omitted from user input.
+
+
Advanced 'default' argument usage
+
Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that is available as input to the validator.
+
Two patterns that you may want to use for this sort of validation include:
+
+
Using HiddenField. This field will be present in validated_data but will not be used in the serializer output representation.
+
Using a standard field with read_only=True, but that also includes a default=… argument. This field will be used in the serializer output representation, but cannot be set directly by the user.
+
+
REST framework includes a couple of defaults that may be useful in this context.
+
CurrentUserDefault
+
A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.
You can use any of Django's existing validators, or write your own custom validators.
+
Function based
+
A validator may be any callable that raises a serializers.ValidationError on failure.
+
def even_number(value):
+ if value % 2 != 0:
+ raise serializers.ValidationError('This field must be an even number.')
+
+
Class based
+
To write a class based validator, use the __call__ method. Class based validators are useful as they allow you to parameterize and reuse behavior.
+
class MultipleOf:
+ def __init__(self, base):
+ self.base = base
+
+ def __call__(self, value):
+ if value % self.base != 0
+ message = 'This field must be a multiple of %d.' % self.base
+ raise serializers.ValidationError(message)
+
+
Using set_context()
+
In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by declaring a set_context method on a class based validator.
+
def set_context(self, serializer_field):
+ # Determine if this is an update or a create operation.
+ # In `__call__` we can then use that information to modify the validation behavior.
+ self.is_update = serializer_field.parent.instance is not None
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/api-guide/views/index.html b/api-guide/views/index.html
index f6c931a46..eac4c5c8c 100644
--- a/api-guide/views/index.html
+++ b/api-guide/views/index.html
@@ -164,6 +164,10 @@
Serializer relations
+
@@ -478,15 +486,22 @@ This method is used to enforce permissions and throttling, and perform content n
REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of Request (rather than the usual Django HttpRequest) and allows them to return a Response (instead of a Django HttpResponse), and allow you to configure how the request is processed.
@api_view()
-
Signature:@api_view(http_method_names)
-
The core of this functionality is the api_view decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:
+
Signature:@api_view(http_method_names=['GET'])
+
The core of this functionality is the api_view decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:
This view will use the default renderers, parsers, authentication classes etc specified in the settings.
+
By default only GET methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so:
To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come after (below) the @api_view decorator. For example, to create a view that uses a throttle to ensure it can only be called once per day by a particular user, use the @throttle_classes decorator, passing a list of throttle classes:
Note: The incoming 3.0 version has now been merged to the master branch on GitHub. For the source of the currently available PyPI version, please see the 2.4.4 tag.
+
Note: This is the documentation for the version 3.0 of REST framework. Documentation for version 2.4 is also available.
@@ -668,7 +678,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/topics/2.2-announcement/index.html b/topics/2.2-announcement/index.html
index a088c6813..16412a7b0 100644
--- a/topics/2.2-announcement/index.html
+++ b/topics/2.2-announcement/index.html
@@ -164,6 +164,10 @@
Serializer relations
+
The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views.
+
This release is incremental in nature. There are some breaking API changes, and upgrading will require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.
+
The difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier.
+
3.0 is the first of three releases that have been funded by our recent Kickstarter campaign.
+
As ever, a huge thank you to our many wonderful sponsors. If you're looking for a Django gig, and want to work with smart community-minded folks, you should probably check out that list and see who's hiring.
+
+
New features
+
Notable features of this new release include:
+
+
Printable representations on serializers that allow you to inspect exactly what fields are present on the instance.
+
Simple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit ModelSerializer class and the explicit Serializer class.
+
A new BaseSerializer class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic.
+
A cleaner fields API including new classes such as ListField and MultipleChoiceField.
Support for overriding how validation errors are handled by your API.
+
A metadata API that allows you to customize how OPTIONS requests are handled by your API.
+
A more compact JSON output with unicode style encoding turned on by default.
+
Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.
+
+
Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two Kickstarter stretch goals - "Feature improvements" and "Admin interface". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release.
+
Below is an in-depth guide to the API changes and migration notes for 3.0.
+
+
Request objects
+
The .data and .query_params properties.
+
The usage of request.DATA and request.FILES is now pending deprecation in favor of a single request.data attribute that contains all the parsed data.
+
Having separate attributes is reasonable for web applications that only ever parse url-encoded or multipart requests, but makes less sense for the general-purpose request parsing that REST framework supports.
+
You may now pass all the request data to a serializer class in a single argument:
+
# Do this...
+ExampleSerializer(data=request.data)
+
+
Instead of passing the files argument separately:
+
# Don't do this...
+ExampleSerializer(data=request.DATA, files=request.FILES)
+
+
The usage of request.QUERY_PARAMS is now pending deprecation in favor of the lowercased request.query_params.
+
+
Serializers
+
Single-step object creation.
+
Previously the serializers used a two-step object creation, as follows:
+
+
Validating the data would create an object instance. This instance would be available as serializer.object.
+
Calling serializer.save() would then save the object instance to the database.
+
+
This style is in-line with how the ModelForm class works in Django, but is problematic for a number of reasons:
+
+
Some data, such as many-to-many relationships, cannot be added to the object instance until after it has been saved. This type of data needed to be hidden in some undocumented state on the object instance, or kept as state on the serializer instance so that it could be used when .save() is called.
+
Instantiating model instances directly means that you cannot use model manager classes for instance creation, e.g. ExampleModel.objects.create(...). Manager classes are an excellent layer at which to enforce business logic and application-level data constraints.
+
The two step process makes it unclear where to put deserialization logic. For example, should extra attributes such as the current user get added to the instance during object creation or during object save?
+
+
We now use single-step object creation, like so:
+
+
Validating the data makes the cleaned data available as serializer.validated_data.
+
Calling serializer.save() then saves and returns the new object instance.
+
+
The resulting API changes are further detailed below.
+
The .create() and .update() methods.
+
The .restore_object() method is now replaced with two separate methods, .create() and .update().
+
These methods also replace the optional .save_object() method, which no longer exists.
+
When using the .create() and .update() methods you should both create and save the object instance. This is in contrast to the previous .restore_object() behavior that would instantiate the object but not save it.
+
The following example from the tutorial previously used restore_object() to handle both creating and updating object instances.
Note that these methods should return the newly created object instance.
+
Use .validated_data instead of .object.
+
You must now use the .validated_data attribute if you need to inspect the data before saving, rather than using the .object attribute, which no longer exists.
+
For example the following code is no longer valid:
+
if serializer.is_valid():
+ name = serializer.object.name # Inspect validated field data.
+ logging.info('Creating ticket "%s"' % name)
+ serializer.object.user = request.user # Include the user when saving.
+ serializer.save()
+
+
Instead of using .object to inspect a partially constructed instance, you would now use .validated_data to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the .save() method as keyword arguments.
+
The corresponding code would now look like this:
+
if serializer.is_valid():
+ name = serializer.validated_data['name'] # Inspect validated field data.
+ logging.info('Creating ticket "%s"' % name)
+ serializer.save(user=request.user) # Include the user when saving.
+
+
Using .is_valid(raise_exception=True)
+
The .is_valid() method now takes an optional boolean flag, raise_exception.
+
Calling .is_valid(raise_exception=True) will cause a ValidationError to be raised if the serializer data contains validation errors. This error will be handled by REST framework's default exception handler, allowing you to remove error response handling from your view code.
+
The handling and formatting of error responses may be altered globally by using the EXCEPTION_HANDLER settings key.
+
This change also means it's now possible to alter the style of error responses used by the built-in generic views, without having to include mixin classes or other overrides.
+
Using serializers.ValidationError.
+
Previously serializers.ValidationError error was simply a synonym for django.core.exceptions.ValidationError. This has now been altered so that it inherits from the standard APIException base class.
+
The reason behind this is that Django's ValidationError class is intended for use with HTML forms and its API makes using it slightly awkward with nested validation errors that can occur in serializers.
+
For most users this change shouldn't require any updates to your codebase, but it is worth ensuring that whenever raising validation errors you should prefer using the serializers.ValidationError exception class, and not Django's built-in exception.
+
We strongly recommend that you use the namespaced import style of import serializers and not from serializers import ValidationError in order to avoid any potential confusion.
+
Change to validate_<field_name>.
+
The validate_<field_name> method hooks that can be attached to serializer classes change their signature slightly and return type. Previously these would take a dictionary of all incoming data, and a key representing the field name, and would return a dictionary including the validated data for that field:
+
def validate_score(self, attrs, source):
+ if attrs['score'] % 10 != 0:
+ raise serializers.ValidationError('This field should be a multiple of ten.')
+ return attrs
+
+
This is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value.
+
def validate_score(self, value):
+ if value % 10 != 0:
+ raise serializers.ValidationError('This field should be a multiple of ten.')
+ return value
+
+
Any ad-hoc validation that applies to more than one field should go in the .validate(self, attrs) method as usual.
+
Because .validate_<field_name> would previously accept the complete dictionary of attributes, it could be used to validate a field depending on the input in another field. Now if you need to do this you should use .validate() instead.
+
You can either return non_field_errors from the validate method by raising a simple ValidationError
+
def validate(self, attrs):
+ # serializer.errors == {'non_field_errors': ['A non field error']}
+ raise serializers.ValidationError('A non field error')
+
+
Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the ValidationError, like so:
+
def validate(self, attrs):
+ # serializer.errors == {'my_field': ['A field error']}
+ raise serializers.ValidationError({'my_field': 'A field error'})
+
+
This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.
+
Removal of transform_<field_name>.
+
The under-used transform_<field_name> on serializer classes is no longer provided. Instead you should just override to_representation() if you need to apply any modifications to the representation style.
+
For example:
+
def to_representation(self, instance):
+ ret = super(UserSerializer, self).to_representation(instance)
+ ret['username'] = ret['username'].lower()
+ return ret
+
+
Dropping the extra point of API means there's now only one right way to do things. This helps with repetition and reinforcement of the core API, rather than having multiple differing approaches.
+
If you absolutely need to preserve transform_<field_name> behavior, for example, in order to provide a simpler 2.x to 3.0 upgrade, you can use a mixin, or serializer base class that add the behavior back in. For example:
+
class BaseModelSerializer(ModelSerializer):
+ """
+ A custom ModelSerializer class that preserves 2.x style `transform_<field_name>` behavior.
+ """
+ def to_representation(self, instance):
+ ret = super(BaseModelSerializer, self).to_representation(instance)
+ for key, value in ret.items():
+ method = getattr(self, 'transform_' + key, None)
+ if method is not None:
+ ret[key] = method(value)
+ return ret
+
+
Differences between ModelSerializer validation and ModelForm.
+
This change also means that we no longer use the .full_clean() method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on ModelSerializer classes that can't also be easily replicated on regular Serializer classes.
+
For the most part this change should be transparent. Field validation and uniqueness checks will still be run as normal, but the implementation is a little different.
+
The one difference that you do need to note is that the .clean() method will not be called as part of serializer validation, as it would be if using a ModelForm. Use the serializer .validate() method to perform a final validation step on incoming data where required.
+
There may be some cases where you really do need to keep validation logic in the model .clean() method, and cannot instead separate it into the serializer .validate(). You can do so by explicitly instantiating a model instance in the .validate() method.
Again, you really should look at properly separating the validation logic out of the model method if possible, but the above might be useful in some backwards compatibility cases, or for an easy migration path.
+
Writable nested serialization.
+
REST framework 2.x attempted to automatically support writable nested serialization, but the behavior was complex and non-obvious. Attempting to automatically handle these case is problematic:
+
+
There can be complex dependencies involved in order of saving multiple related model instances.
+
It's unclear what behavior the user should expect when related models are passed None data.
+
It's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records.
+
+
Using the depth option on ModelSerializer will now create read-only nested serializers by default.
+
If you try to use a writable nested serializer without writing a custom create() and/or update() method you'll see an assertion error when you attempt to save the serializer. For example:
+
>>> class ProfileSerializer(serializers.ModelSerializer):
+>>> class Meta:
+>>> model = Profile
+>>> fields = ('address', 'phone')
+>>>
+>>> class UserSerializer(serializers.ModelSerializer):
+>>> profile = ProfileSerializer()
+>>> class Meta:
+>>> model = User
+>>> fields = ('username', 'email', 'profile')
+>>>
+>>> data = {
+>>> 'username': 'lizzy',
+>>> 'email': 'lizzy@example.com',
+>>> 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}
+>>> }
+>>>
+>>> serializer = UserSerializer(data=data)
+>>> serializer.save()
+AssertionError: The `.create()` method does not support nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields.
+
+
To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the create() and/or update() methods explicitly.
+
class UserSerializer(serializers.ModelSerializer):
+ profile = ProfileSerializer()
+
+ class Meta:
+ model = User
+ fields = ('username', 'email', 'profile')
+
+ def create(self, validated_data):
+ profile_data = validated_data.pop('profile')
+ user = User.objects.create(**validated_data)
+ Profile.objects.create(user=user, **profile_data)
+ return user
+
+
The single-step object creation makes this far simpler and more obvious than the previous .restore_object() behavior.
+
Printable serializer representations.
+
Serializer instances now support a printable representation that allows you to inspect the fields present on the instance.
Let's create a simple ModelSerializer class corresponding to the LocationRating model.
+
class LocationRatingSerializer(serializer.ModelSerializer):
+ class Meta:
+ model = LocationRating
+
+
We can now inspect the serializer representation in the Django shell, using python manage.py shell...
+
>>> serializer = LocationRatingSerializer()
+>>> print(serializer) # Or use `print serializer` in Python 2.x
+LocationRatingSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ location = CharField(max_length=100)
+ rating = IntegerField()
+ created_by = PrimaryKeyRelatedField(queryset=User.objects.all())
+
+
The extra_kwargs option.
+
The write_only_fields option on ModelSerializer has been moved to PendingDeprecation and replaced with a more generic extra_kwargs.
+
class MySerializer(serializer.ModelSerializer):
+ class Meta:
+ model = MyModel
+ fields = ('id', 'email', 'notes', 'is_admin')
+ extra_kwargs = {
+ 'is_admin': {'write_only': True}
+ }
+
+
Alternatively, specify the field explicitly on the serializer class:
+
class MySerializer(serializer.ModelSerializer):
+ is_admin = serializers.BooleanField(write_only=True)
+
+ class Meta:
+ model = MyModel
+ fields = ('id', 'email', 'notes', 'is_admin')
+
+
The read_only_fields option remains as a convenient shortcut for the more common case.
+
Changes to HyperlinkedModelSerializer.
+
The view_name and lookup_field options have been moved to PendingDeprecation. They are no longer required, as you can use the extra_kwargs argument instead:
+
class MySerializer(serializer.HyperlinkedModelSerializer):
+ class Meta:
+ model = MyModel
+ fields = ('url', 'email', 'notes', 'is_admin')
+ extra_kwargs = {
+ 'url': {'lookup_field': 'uuid'}
+ }
+
+
Alternatively, specify the field explicitly on the serializer class:
+
class MySerializer(serializer.HyperlinkedModelSerializer):
+ url = serializers.HyperlinkedIdentityField(
+ view_name='mymodel-detail',
+ lookup_field='uuid'
+ )
+
+ class Meta:
+ model = MyModel
+ fields = ('url', 'email', 'notes', 'is_admin')
+
+
Fields for model methods and properties.
+
With ModelSerializer you can now specify field names in the fields option that refer to model methods or properties. For example, suppose you have the following model:
The ListSerializer class has now been added, and allows you to create base serializer classes for only accepting multiple inputs.
+
class MultipleUserSerializer(ListSerializer):
+ child = UserSerializer()
+
+
You can also still use the many=True argument to serializer classes. It's worth noting that many=True argument transparently creates a ListSerializer instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase.
+
You will typically want to continue to use the existing many=True flag rather than declaring ListSerializer classes explicitly, but declaring the classes explicitly can be useful if you need to write custom create or update methods for bulk updates, or provide for other custom behavior.
+
See also the new ListField class, which validates input in the same way, but does not include the serializer interfaces of .is_valid(), .data, .save() and so on.
+
The BaseSerializer class.
+
REST framework now includes a simple BaseSerializer class that can be used to easily support alternative serialization and deserialization styles.
+
This class implements the same basic API as the Serializer class:
+
+
.data - Returns the outgoing primitive representation.
+
.is_valid() - Deserializes and validates incoming data.
+
.validated_data - Returns the validated incoming data.
+
.errors - Returns an errors during validation.
+
.save() - Persists the validated data into an object instance.
+
+
There are four methods that can be overridden, depending on what functionality you want the serializer class to support:
+
+
.to_representation() - Override this to support serialization, for read operations.
+
.to_internal_value() - Override this to support deserialization, for write operations.
+
.create() and .update() - Override either or both of these to support saving instances.
+
+
Because this class provides the same interface as the Serializer class, you can use it with the existing generic class based views exactly as you would for a regular Serializer or ModelSerializer.
+
The only difference you'll notice when doing so is the BaseSerializer 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.
+
Read-only BaseSerializer classes.
+
To implement a read-only serializer using the BaseSerializer class, we just need to override the .to_representation() method. Let's take a look at an example using a simple Django model:
+
class HighScore(models.Model):
+ created = models.DateTimeField(auto_now_add=True)
+ player_name = models.CharField(max_length=10)
+ score = models.IntegerField()
+
+
It's simple to create a read-only serializer for converting HighScore instances into primitive data types.
To create a read-write serializer we first need to implement a .to_internal_value() method. This method returns the validated values that will be used to construct the object instance, and may raise a ValidationError if the supplied data is in an incorrect format.
+
Once you've implemented .to_internal_value(), the basic validation API will be available on the serializer, and you will be able to use .is_valid(), .validated_data and .errors.
+
If you want to also support .save() you'll need to also implement either or both of the .create() and .update() methods.
+
Here's a complete example of our previous HighScoreSerializer, that's been updated to support both read and write operations.
+
class HighScoreSerializer(serializers.BaseSerializer):
+ def to_internal_value(self, data):
+ score = data.get('score')
+ player_name = data.get('player_name')
+
+ # Perform the data validation.
+ if not score:
+ raise ValidationError({
+ 'score': 'This field is required.'
+ })
+ if not player_name:
+ raise ValidationError({
+ 'player_name': 'This field is required.'
+ })
+ if len(player_name) > 10:
+ raise ValidationError({
+ '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)
+
+
Creating new generic serializers with BaseSerializer.
+
The BaseSerializer 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.
+
The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.
+
class ObjectSerializer(serializers.BaseSerializer):
+ """
+ A read-only serializer that coerces arbitrary complex objects
+ into primitive representations.
+ """
+ def to_representation(self, obj):
+ for attribute_name in dir(obj):
+ attribute = getattr(obj, attribute_name)
+ if attribute_name('_'):
+ # Ignore private attributes.
+ pass
+ elif hasattr(attribute, '__call__'):
+ # Ignore methods and other callables.
+ pass
+ elif isinstance(attribute, (str, int, bool, float, type(None))):
+ # Primitive types can be passed through unmodified.
+ output[attribute_name] = attribute
+ elif isinstance(attribute, list):
+ # Recursively deal with items in lists.
+ output[attribute_name] = [
+ self.to_representation(item) for item in attribute
+ ]
+ elif isinstance(attribute, dict):
+ # Recursively deal with items in dictionaries.
+ output[attribute_name] = {
+ str(key): self.to_representation(value)
+ for key, value in attribute.items()
+ }
+ else:
+ # Force anything else to its string representation.
+ output[attribute_name] = str(attribute)
+
+
+
Serializer fields
+
The Field and ReadOnly field classes.
+
There are some minor tweaks to the field base classes.
+
Previously we had these two base classes:
+
+
Field as the base class for read-only fields. A default implementation was included for serializing data.
+
WritableField as the base class for read-write fields.
+
+
We now use the following:
+
+
Field is the base class for all fields. It does not include any default implementation for either serializing or deserializing data.
+
ReadOnlyField is a concrete implementation for read-only fields that simply returns the attribute value without modification.
+
+
The required, allow_none, allow_blank and default arguments.
+
REST framework now has more explicit and clear control over validating empty values for fields.
+
Previously the meaning of the required=False keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be None or the empty string.
+
We now have a better separation, with separate required, allow_none and allow_blank arguments.
+
The following set of arguments are used to control validation of empty values:
+
+
required=False: The value does not need to be present in the input, and will not be passed to .create() or .update() if it is not seen.
+
default=<value>: The value does not need to be present in the input, and a default value will be passed to .create() or .update() if it is not seen.
+
allow_none=True: None is a valid input.
+
allow_blank=True: '' is valid input. For CharField and subclasses only.
+
+
Typically you'll want to use required=False if the corresponding model field has a default value, and additionally set either allow_none=True or allow_blank=True if required.
+
The default argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the required argument when a default is specified, and doing so will result in an error.
+
Coercing output types.
+
The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an IntegerField would return a string output if the attribute value was a string. We now more strictly coerce to the correct return type, leading to more constrained and expected behavior.
+
Removal of .validate().
+
The .validate() method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override to_internal_value().
+
class UppercaseCharField(serializers.CharField):
+ def to_internal_value(self, data):
+ value = super(UppercaseCharField, self).to_internal_value(data)
+ if value != value.upper():
+ raise serializers.ValidationError('The input should be uppercase only.')
+ return value
+
+
Previously validation errors could be raised in either .to_native() or .validate(), making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.
+
The ListField class.
+
The ListField class has now been added. This field validates list input. It takes a child keyword argument which is used to specify the field used to validate each item in the list. For example:
You can also use a declarative style to create new subclasses of ListField, like this:
+
class ScoresField(ListField):
+ child = IntegerField(min_value=0, max_value=100)
+
+
We can now use the ScoresField class inside another serializer:
+
scores = ScoresField()
+
+
See also the new ListSerializer class, which validates input in the same way, but also includes the serializer interfaces of .is_valid(), .data, .save() and so on.
+
The ChoiceField class may now accept a flat list.
+
The ChoiceField class may now accept a list of choices in addition to the existing style of using a list of pairs of (name, display_value). The following is now valid:
+
color = ChoiceField(choices=['red', 'green', 'blue'])
+
+
The MultipleChoiceField class.
+
The MultipleChoiceField class has been added. This field acts like ChoiceField, but returns a set, which may include none, one or many of the valid choices.
+
Changes to the custom field API.
+
The from_native(self, value) and to_native(self, data) method names have been replaced with the more obviously named to_internal_value(self, data) and to_representation(self, value).
+
The field_from_native() and field_to_native() methods are removed. Previously you could use these methods if you wanted to customise the behaviour in a way that did not simply lookup the field value from the object. For example...
+
def field_to_native(self, obj, field_name):
+ """A custom read-only field that returns the class name."""
+ return obj.__class__.__name__
+
+
Now if you need to access the entire object you'll instead need to override one or both of the following:
+
+
Use get_attribute to modify the attribute value passed to to_representation().
+
Use get_value to modify the data value passed to_internal_value().
+
+
For example:
+
def get_attribute(self, obj):
+ # Pass the entire object through to `to_representation()`,
+ # instead of the standard attribute lookup.
+ return obj
+
+def to_representation(self, value):
+ return value.__class__.__name__
+
+
Explicit queryset required on relational fields.
+
Previously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a ModelSerializer.
+
This code would be valid in 2.4.3:
+
class AccountSerializer(serializers.ModelSerializer):
+ organizations = serializers.SlugRelatedField(slug_field='name')
+
+ class Meta:
+ model = Account
+
The queryset argument is now always required for writable relational fields.
+This removes some magic and makes it easier and more obvious to move between implicit ModelSerializer classes and explicit Serializer classes.
+
class AccountSerializer(serializers.ModelSerializer):
+ organizations = serializers.SlugRelatedField(
+ slug_field='name',
+ queryset=Organization.objects.all()
+ )
+
+ class Meta:
+ model = Account
+
+
The queryset argument is only ever required for writable fields, and is not required or valid for fields with read_only=True.
+
Optional argument to SerializerMethodField.
+
The argument to SerializerMethodField is now optional, and defaults to get_<field_name>. For example the following is valid:
+
class AccountSerializer(serializers.Serializer):
+ # `method_name='get_billing_details'` by default.
+ billing_details = serializers.SerializerMethodField()
+
+ def get_billing_details(self, account):
+ return calculate_billing(account)
+
+
In order to ensure a consistent code style an assertion error will be raised if you include a redundant method name argument that matches the default method name. For example, the following code will raise an error:
I've see several codebases that unnecessarily include the source argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that source is usually not required.
+
The following usage will now raise an error:
+
email = serializers.EmailField(source='email')
+
+
The UniqueValidator and UniqueTogetherValidator classes.
+
REST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit Serializer class instead of using ModelSerializer.
+
The UniqueValidator should be applied to a serializer field, and takes a single queryset argument.
+
from rest_framework import serializers
+from rest_framework.validators import UniqueValidator
+
+class OrganizationSerializer(serializers.Serializer):
+ url = serializers.HyperlinkedIdentityField(view_name='organization_detail')
+ created = serializers.DateTimeField(read_only=True)
+ name = serializers.CharField(
+ max_length=100,
+ validators=UniqueValidator(queryset=Organization.objects.all())
+ )
+
+
The UniqueTogetherValidator should be applied to a serializer, and takes a queryset argument and a fields argument which should be a list or tuple of field names.
+
class RaceResultSerializer(serializers.Serializer):
+ category = serializers.ChoiceField(['5k', '10k'])
+ position = serializers.IntegerField()
+ name = serializers.CharField(max_length=100)
+
+ class Meta:
+ validators = [UniqueTogetherValidator(
+ queryset=RaceResult.objects.all(),
+ fields=('category', 'position')
+ )]
+
+
The UniqueForDateValidator classes.
+
REST framework also now includes explicit validator classes for validating the unique_for_date, unique_for_month, and unique_for_year model field constraints. These are used internally instead of calling into Model.full_clean().
+
These classes are documented in the Validators section of the documentation.
+
+
Generic views
+
Simplification of view logic.
+
The view logic for the default method handlers has been significantly simplified, due to the new serializers API.
+
Changes to pre/post save hooks.
+
The pre_save and post_save hooks no longer exist, but are replaced with perform_create(self, serializer) and perform_update(self, serializer).
+
These methods should save the object instance by calling serializer.save(), adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior.
+
For example:
+
def perform_create(self, serializer):
+ # Include the owner attribute directly, rather than from request data.
+ instance = serializer.save(owner=self.request.user)
+ # Perform a custom post-save action.
+ send_email(instance.to_email, instance.message)
+
+
The pre_delete and post_delete hooks no longer exist, and are replaced with .perform_destroy(self, instance), which should delete the instance and perform any custom actions.
The .object and .object_list attributes are no longer set on the view instance. Treating views as mutable object instances that store state during the processing of the view tends to be poor design, and can lead to obscure flow logic.
+
I would personally recommend that developers treat view instances as immutable objects in their application code.
+
PUT as create.
+
Allowing PUT as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning 404 responses.
+
Both styles "PUT as 404" and "PUT as create" can be valid in different circumstances, but we've now opted for the 404 behavior as the default, due to it being simpler and more obvious.
The generic views now raise ValidationFailed exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a 400 Bad Request response directly.
+
This change means that you can now easily customize the style of error responses across your entire API, without having to modify any of the generic views.
+
+
The metadata API
+
Behavior for dealing with OPTIONS requests was previously built directly into the class based views. This has now been properly separated out into a Metadata API that allows the same pluggable style as other API policies in REST framework.
+
This makes it far easier to use a different style for OPTIONS responses throughout your API, and makes it possible to create third-party metadata policies.
+
+
Serializers as HTML forms
+
REST framework 3.0 includes templated HTML form rendering for serializers.
+
This API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release.
+
Significant changes that you do need to be aware of include:
+
+
Nested HTML forms are now supported, for example, a UserSerializer with a nested ProfileSerializer will now render a nested fieldset when used in the browsable API.
+
Nested lists of HTML forms are not yet supported, but are planned for 3.1.
+
Because we now use templated HTML form generation, the widget option is no longer available for serializer fields. You can instead control the template that is used for a given field, by using the style dictionary.
+
+
The style keyword argument for serializer fields.
+
The style keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the HTMLFormRenderer uses the base_template key to determine which template to render the field with.
+
For example, to use a textarea control instead of the default input control, you would use the following…
This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.
+
+
API style
+
There are some improvements in the default style we use in our API responses.
+
Unicode JSON by default.
+
Unicode JSON is now the default. The UnicodeJSONRenderer class no longer exists, and the UNICODE_JSON setting has been added. To revert this behavior use the new setting:
+
REST_FRAMEWORK = {
+ 'UNICODE_JSON': False
+}
+
+
Compact JSON by default.
+
We now output compact JSON in responses by default. For example, we return:
+
{"email":"amy@example.com","is_admin":true}
+
+
Instead of the following:
+
{"email": "amy@example.com", "is_admin": true}
+
+
The COMPACT_JSON setting has been added, and can be used to revert this behavior if needed:
+
REST_FRAMEWORK = {
+ 'COMPACT_JSON': False
+}
+
+
File fields as URLs
+
The FileField and ImageField classes are now represented as URLs by default. You should ensure you set Django's standard MEDIA_URL setting appropriately, and ensure your application serves the uploaded files.
+
You can revert this behavior, and display filenames in the representation by using the UPLOADED_FILES_USE_URL settings key:
Also note that you should pass the request object to the serializer as context when instantiating it, so that a fully qualified URL can be returned. Returned URLs will then be of the form https://example.com/url_path/filename.txt. For example:
If the request is omitted from the context, the returned URLs will be of the form /url_path/filename.txt.
+
Throttle headers using Retry-After.
+
The custom X-Throttle-Wait-Second header has now been dropped in favor of the standard Retry-After header. You can revert this behavior if needed by writing a custom exception handler for your application.
+
Date and time objects as ISO-8859-1 strings in serializer data.
+
Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as Date, Time and DateTime objects, and later coerced to strings by the renderer.
+
You can modify this behavior globally by settings the existing DATE_FORMAT, DATETIME_FORMAT and TIME_FORMAT settings keys. Setting these values to None instead of their default value of 'iso-8859-1' will result in native objects being returned in serializer data.
You can also modify serializer fields individually, using the date_format, time_format and datetime_format arguments:
+
# Return `DateTime` instances in `serializer.data`, not strings.
+created = serializers.DateTimeField(format=None)
+
+
Decimals as strings in serializer data.
+
Decimals are now coerced to strings by default in the serializer output. Previously they were returned as Decimal objects, and later coerced to strings by the renderer.
+
You can modify this behavior globally by using the COERCE_DECIMAL_TO_STRING settings key.
Or modify it on an individual serializer field, using the coerce_to_string keyword argument.
+
# Return `Decimal` instances in `serializer.data`, not strings.
+amount = serializers.DecimalField(
+ max_digits=10,
+ decimal_places=2,
+ coerce_to_string=False
+)
+
+
The default JSON renderer will return float objects for un-coerced Decimal instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.
+
+
Miscellaneous notes
+
+
The serializer ChoiceField does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.
+
Due to the new templated form rendering, the 'widget' option is no longer valid. This means there's no easy way of using third party "autocomplete" widgets for rendering select inputs that contain a large number of choices. You'll either need to use a regular select or a plain text input. We may consider addressing this in 3.1 or 3.2 if there's sufficient demand.
+
+
+
What's coming next
+
3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes.
+
The 3.1 release is planned to address improvements in the following components:
+
+
Public API for using serializers as HTML forms.
+
Request parsing, mediatypes & the implementation of the browsable API.
+
Introduction of a new pagination API.
+
Better support for API versioning.
+
+
The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.
You can override the BrowsableAPIRenderer.get_context() method to customise the context that gets passed to the template.
Not using base.html
For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have api.html extend base.html. Then the page content and capabilities are entirely up to you.
-
Autocompletion
-
When a ChoiceField has too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly. One solution is to replace the selector by an autocomplete widget, that only loads and renders a subset of the available options as needed.
When a relationship or ChoiceField has too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly.
+
The simplest option in this case is to replace the select input with a standard text input. For example:
You can now add the autocomplete_light.ChoiceWidget widget to the serializer field.
-
import autocomplete_light
-
-class BookSerializer(serializers.ModelSerializer):
- author = serializers.ChoiceField(
- widget=autocomplete_light.ChoiceWidget('AuthorAutocomplete')
- )
-
- class Meta:
- model = Book
-
-
-
-
Screenshot of the autocomplete-light widget
+
Autocomplete
+
An alternative, but more complex option would be to replace the input with an autocomplete widget, that only loads and renders a subset of the available options as needed. If you need to do this you'll need to do some work to build a custom autocomplete HTML template yourself.
+
There are a variety of packages for autocomplete widgets, such as django-autocomplete-light, that you may want to refer to. Note that you will not be able to simply include these components as standard widgets, but will need to write the HTML template explicitly. This is because REST framework 3.0 no longer supports the widget keyword argument since it now uses templated HTML generation.
+
Better support for autocomplete inputs is planned in future versions.
@@ -445,7 +453,7 @@ as well as how to support content types other than form-encoded data.
diff --git a/topics/contributing/index.html b/topics/contributing/index.html
index 690b9dc5c..a8ec0e2b1 100644
--- a/topics/contributing/index.html
+++ b/topics/contributing/index.html
@@ -164,6 +164,10 @@
Serializer relations
+
Bugfix: Validation errors instead of exceptions when related fields receive incorrect types.
Bugfix: Handle ObjectDoesNotExist exception when serializing null reverse one-to-one
-
Note: Prior to 2.1.16, The Decimals would render in JSON using floating point if simplejson was installed, but otherwise render using string notation. Now that use of simplejson has been deprecated, Decimals will consistently render using string notation. See #582 for more details.
+
Note: Prior to 2.1.16, The Decimals would render in JSON using floating point if simplejson was installed, but otherwise render using string notation. Now that use of simplejson has been deprecated, Decimals will consistently render using string notation. See ticket 582 for more details.
Allow views to specify template used by TemplateRenderer
-
More consistent error responses
-
Some serializer fixes
-
Fix internet explorer ajax behavior
-
Minor xml and yaml fixes
-
Improve setup (e.g. use staticfiles, not the defunct ADMIN_MEDIA_PREFIX)
-
Sensible absolute URL generation, not using hacky set_script_prefix
-
-
-
0.3.x series
-
0.3.3
-
-
Added DjangoModelPermissions class to support django.contrib.auth style permissions.
-
Use staticfiles for css files.
-
Easier to override. Won't conflict with customized admin styles (e.g. grappelli)
-
Templates are now nicely namespaced.
-
Allows easier overriding.
-
Drop implied 'pk' filter if last arg in urlconf is unnamed.
-
Too magical. Explicit is better than implicit.
-
Saner template variable auto-escaping.
-
Tidier setup.py
-
Updated for URLObject 2.0
-
Bugfixes:
-
Bug with PerUserThrottling when user contains unicode chars.
-
-
0.3.2
-
-
Bugfixes:
-
Fix 403 for POST and PUT from the UI with UserLoggedInAuthentication (#115)
-
serialize_model method in serializer.py may cause wrong value (#73)
-
Fix Error when clicking OPTIONS button (#146)
-
And many other fixes
-
Remove short status codes
-
Zen of Python: "There should be one-- and preferably only one --obvious way to do it."
-
get_name, get_description become methods on the view - makes them overridable.
-
Improved model mixin API - Hooks for build_query, get_instance_data, get_model, get_queryset, get_ordering
-
-
0.3.1
-
-
[not documented]
-
-
0.3.0
-
-
JSONP Support
-
Bugfixes, including support for latest markdown release
-
-
-
0.2.x series
-
0.2.4
-
-
Fix broken IsAdminUser permission.
-
OPTIONS support.
-
XMLParser.
-
Drop mentions of Blog, BitBucket.
-
-
0.2.3
-
-
Fix some throttling bugs.
-
X-Throttle header on throttling.
-
Support for nesting resources on related models.
-
-
0.2.2
-
-
Throttling support complete.
-
-
0.2.1
-
-
Couple of simple bugfixes over 0.2.0
-
-
0.2.0
-
-
-
Big refactoring changes since 0.1.0, ask on the discussion group if anything isn't clear.
- The public API has been massively cleaned up. Expect it to be fairly stable from here on in.
-
-
-
Resource becomes decoupled into View and Resource, your views should now inherit from View, not Resource.
-
-
-
The handler functions on views .get() .put() .post() etc, no longer have the content and auth args.
- Use self.CONTENT inside a view to access the deserialized, validated content.
- Use self.user inside a view to access the authenticated user.
-
-
-
allowed_methods and anon_allowed_methods are now defunct. if a method is defined, it's available.
- The permissions attribute on a View is now used to provide generic permissions checking.
- Use permission classes such as FullAnonAccess, IsAuthenticated or IsUserOrIsAnonReadOnly to set the permissions.
-
-
-
The authenticators class becomes authentication. Class names change to Authentication.
-
-
-
The emitters class becomes renderers. Class names change to Renderers.
-
-
-
ResponseException becomes ErrorResponse.
-
-
-
The mixin classes have been nicely refactored, the basic mixins are now RequestMixin, ResponseMixin, AuthMixin, and ResourceMixin
- You can reuse these mixin classes individually without using the View class.
-
-
-
-
0.1.x series
-
0.1.1
-
-
Final build before pulling in all the refactoring changes for 0.2, in case anyone needs to hang on to 0.1.
First off, the disclaimer. The name "Django REST framework" was chosen simply to sure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".
-
If you are serious about designing a Hypermedia APIs, you should look to resources outside of this documentation to help inform your design choices.
+
First off, the disclaimer. The name "Django REST framework" was decided back in early 2011 and was chosen simply to sure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".
+
If you are serious about designing a Hypermedia API, you should look to resources outside of this documentation to help inform your design choices.
The following fall into the "required reading" category.
It is self evident that REST framework makes it possible to build Hypermedia APIs. The browsable API that it offers is built on HTML - the hypermedia language of the web.
What REST framework doesn't do is give you is machine readable hypermedia formats such as HAL, Collection+JSON, JSON API or HTML microformats by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.
+
What REST framework doesn't do is give you is machine readable hypermedia formats such as HAL, Collection+JSON, JSON API or HTML microformats by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.
@@ -405,7 +413,7 @@ the Design of Network-based Software Architectures.
diff --git a/topics/third-party-resources/index.html b/topics/third-party-resources/index.html
index 0e3329084..529a7b5aa 100644
--- a/topics/third-party-resources/index.html
+++ b/topics/third-party-resources/index.html
@@ -164,6 +164,10 @@
Serializer relations
+
Third Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases.
-
We support, encourage and strongly favour the creation of Third Party Packages to encapsulate new behaviour rather than adding additional functionality directly to Django REST Framework.
-
We aim to make creating Third Party Packages as easy as possible, whilst keeping the simplicity of the core API and ensuring that maintenance of the main project remains under control. If a Third Party Package proves popular it is relatively easy to move it into the main project; removing features is much more problematic.
-
If you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to dicuss ideas on the Mailing List.
+
We support, encourage and strongly favor the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework.
+
We aim to make creating third party packages as easy as possible, whilst keeping a simple and well maintained core API. By promoting third party packages we ensure that the responsibility for a package remains with its author. If a package proves suitably popular it can always be considered for inclusion into the core REST framework.
+
If you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to discuss ideas on the Mailing List.
How to create a Third Party Package
Creating your package
You can use this cookiecutter template for creating reusable Django REST Framework packages quickly. Cookiecutter creates projects from project templates. While optional, this cookiecutter template includes best practices from Django REST framework and other packages, as well as a Travis CI configuration, Tox configuration, and a sane setup.py for easy PyPI registration/distribution.
@@ -581,7 +589,7 @@ You probably want to also tag the version now:
diff --git a/tutorial/1-serialization/index.html b/tutorial/1-serialization/index.html
index acdb0893b..dda47f721 100644
--- a/tutorial/1-serialization/index.html
+++ b/tutorial/1-serialization/index.html
@@ -164,6 +164,10 @@
Serializer relations
+
From this point we're going to really start covering the core of REST framework.
Let's introduce a couple of essential building blocks.
Request objects
-
REST framework introduces a Request object that extends the regular HttpRequest, and provides more flexible request parsing. The core functionality of the Request object is the request.DATA attribute, which is similar to request.POST, but more useful for working with Web APIs.
+
REST framework introduces a Request object that extends the regular HttpRequest, and provides more flexible request parsing. The core functionality of the Request object is the request.data attribute, which is similar to request.POST, but more useful for working with Web APIs.
request.POST # Only handles form data. Only works for 'POST' method.
-request.DATA # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
+request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
Response objects
REST framework also introduces a Response object, which is a type of TemplateResponse that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.
@@ -407,7 +415,7 @@ request.DATA # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' met
The APIView class for working with class based views.
These wrappers provide a few bits of functionality such as making sure you receive Request instances in your view, and adding context to Response objects so that content negotiation can be performed.
-
The wrappers also provide behaviour such as returning 405 Method Not Allowed responses when appropriate, and handling any ParseError exception that occurs when accessing request.DATA with malformed input.
+
The wrappers also provide behaviour such as returning 405 Method Not Allowed responses when appropriate, and handling any ParseError exception that occurs when accessing request.data with malformed input.
Pulling it all together
Okay, let's go ahead and start using these new components to write a few views.
We don't need our JSONResponse class in views.py anymore, so go ahead and delete that. Once that's done we can start refactoring our views slightly.
This should all feel very familiar - it is not a lot different from working with regular Django views.
-
Notice that we're no longer explicitly tying our requests or responses to a given content type. request.DATA can handle incoming json requests, but it can also handle yaml and other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.
+
Notice that we're no longer explicitly tying our requests or responses to a given content type. request.data can handle incoming json requests, but it can also handle yaml and other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.
Adding optional format suffixes to our URLs
To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as http://example.com/api/items/4.json.
Start by adding a format keyword argument to both of the views, like so.