django-rest-framework/docs/api-guide/serializers.md

470 lines
22 KiB
Markdown
Raw Normal View History

2012-09-09 01:06:13 +04:00
<a class="github" href="serializers.py"></a>
2012-09-01 23:26:27 +04:00
# Serializers
> Expanding the usefulness of the serializers is something that we would
like to address. However, it's not a trivial problem, and it
2012-12-29 16:15:15 +04:00
will take some serious design work.
2012-09-01 23:26:27 +04:00
>
> &mdash; Russell Keith-Magee, [Django users group][cite]
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.
## Declaring Serializers
Let's start by creating a simple object we can use for example purposes:
class Comment(object):
def __init__(self, email, content, created=None):
self.email = email
self.content = content
self.created = created or datetime.datetime.now()
comment = Comment(email='leila@example.com', content='foo bar')
We'll declare a serializer that we can use to serialize and deserialize `Comment` objects.
2013-03-17 23:59:13 +04:00
2012-09-01 23:26:27 +04:00
Declaring a serializer looks very similar to declaring a form:
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
def restore_object(self, attrs, instance=None):
2013-03-17 23:59:13 +04:00
"""
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.title = attrs.get('title', instance.title)
instance.content = attrs.get('content', instance.content)
instance.created = attrs.get('created', instance.created)
2012-09-01 23:26:27 +04:00
return instance
return Comment(**attrs)
2013-03-19 18:26:48 +04:00
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.
2012-09-01 23:26:27 +04:00
## 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.
serializer = CommentSerializer(comment)
2012-09-01 23:26:27 +04:00
serializer.data
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)}
At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into `json`.
json = JSONRenderer().render(serializer.data)
json
2012-09-01 23:26:27 +04:00
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
## Deserializing objects
Deserialization is similar. First we parse a stream into python native datatypes...
stream = StringIO(json)
2012-09-01 23:26:27 +04:00
data = JSONParser().parse(stream)
...then we restore those native datatypes into a fully populated object instance.
serializer = CommentSerializer(data=data)
2012-09-01 23:26:27 +04:00
serializer.is_valid()
# True
serializer.object
# <Comment object at 0x10633b2d0>
>>> serializer.deserialize('json', stream)
When deserializing data, we can either create a new instance, or update an existing instance.
serializer = CommentSerializer(data=data) # Create new instance
serializer = CommentSerializer(comment, data=data) # Update `instance`
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 `instance` with partial data
2012-09-01 23:26:27 +04:00
## 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:
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.']}
2013-03-19 18:26:48 +04:00
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.
2012-09-01 23:26:27 +04:00
When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items.
#### Field-level validation
You can specify custom field-level validation by adding `.validate_<fieldname>` methods to your `Serializer` subclass. These are analagous 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:
from rest_framework import serializers
class BlogPostSerializer(serializers.Serializer):
title = serializers.CharField(max_length=100)
content = serializers.CharField()
def validate_title(self, attrs, source):
"""
Check that the blog post is about Django.
"""
value = attrs[source]
if "django" not in value.lower():
raise serializers.ValidationError("Blog post is not about Django")
return attrs
#### Object-level validation
2012-12-28 16:59:24 +04:00
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:
from rest_framework import serializers
class EventSerializer(serializers.Serializer):
2013-02-12 17:55:00 +04:00
description = serializers.CharField(max_length=100)
2012-12-28 16:59:24 +04:00
start = serializers.DateTimeField()
finish = serializers.DateTimeField()
def validate(self, attrs):
"""
Check that the start is before the stop.
"""
if attrs['start'] < attrs['finish']:
raise serializers.ValidationError("finish must occur after start")
return attrs
## Saving object state
To save the deserialized objects created by a serializer, call the `.save()` method:
if serializer.is_valid():
serializer.save()
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.
2012-10-24 14:39:17 +04:00
The generic views provided by REST framework call the `.save()` method when updating or creating entities.
2012-10-24 14:39:17 +04:00
2012-09-01 23:26:27 +04:00
## 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.
2012-09-01 23:26:27 +04:00
The `Serializer` class is itself a type of `Field`, and can be used to represent relationships where one object type is nested inside another.
class UserSerializer(serializers.Serializer):
email = serializers.EmailField()
username = serializers.CharField(max_length=100)
2012-09-01 23:26:27 +04:00
class CommentSerializer(serializers.Serializer):
user = UserSerializer()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
If a nested representation may optionally accept the `None` value you should pass the `required=False` flag to the nested serializer.
class CommentSerializer(serializers.Serializer):
user = UserSerializer(required=False) # May be an anonymous user.
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
Similarly if a nested representation should be a list of items, you should the `many=True` flag to the nested serialized.
class CommentSerializer(serializers.Serializer):
user = UserSerializer(required=False)
edits = EditItemSerializer(many=True) # A nested list of 'edit' items.
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
2012-10-29 00:43:43 +04:00
---
**Note**: Nested serializers are only suitable for read-only representations, as there are cases where they would have ambiguous or non-obvious behavior if used when updating instances. For read-write representations you should always use a flat representation, by using one of the `RelatedField` subclasses.
---
## Dealing with multiple objects
2013-02-12 17:55:00 +04:00
The `Serializer` class can also handle serializing or deserializing lists of objects.
2013-02-12 17:55:00 +04:00
#### Serializing multiple objects
2013-02-12 17:55:00 +04:00
To serialize a queryset or list of objects instead of a single object instance, you should pass the `many=True` flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.
queryset = Book.objects.all()
serializer = BookSerializer(queryset, many=True)
2013-02-12 17:55:00 +04:00
serializer.data
# [
# {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},
# {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},
# {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}
# ]
2013-02-12 17:55:00 +04:00
#### Deserializing multiple objects for creation
2012-09-01 23:26:27 +04:00
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.
2012-09-01 23:26:27 +04:00
This allows you to write views that create multiple items when a `POST` request is made.
2012-09-01 23:26:27 +04:00
For example:
2012-09-01 23:26:27 +04:00
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
serialize.save() # `.save()` will be called on each updated or newly created instance.
2013-03-26 00:26:34 +04:00
By default bulk updates will be limited to updating instances that already exist in the provided queryset.
2013-03-26 00:26:34 +04:00
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.
2013-03-26 00:26:34 +04:00
serializer = BookSerializer(queryset, data=data, many=True, allow_add_remove=True)
serializer.is_valid()
# True
2013-03-26 00:26:34 +04:00
serializer.save() # `.save()` will be called on updated or newly created instances.
# `.delete()` will be called on any other items in the `queryset`.
2013-03-26 00:28:17 +04:00
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
2013-03-26 11:48:53 +04:00
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):
2012-09-01 23:26:27 +04:00
"""
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.
2012-09-01 23:26:27 +04:00
"""
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.
## 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:
serializer = AccountSerializer(account, context={'request': request})
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.
2012-09-01 23:26:27 +04:00
---
2013-05-05 19:48:12 +04:00
# ModelSerializer
2012-09-01 23:26:27 +04:00
Often you'll want serializer classes that map closely to model definitions.
2012-11-07 00:18:49 +04:00
The `ModelSerializer` class lets you automatically create a Serializer class with fields that correspond to the Model fields.
2012-09-01 23:26:27 +04:00
2012-10-09 20:49:04 +04:00
class AccountSerializer(serializers.ModelSerializer):
2012-09-01 23:26:27 +04:00
class Meta:
model = Account
2013-02-24 02:01:29 +04:00
By default, all the model fields on the class will be mapped to corresponding serializer fields.
2013-05-05 19:48:12 +04:00
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.
## 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:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'account_name', 'users', 'created')
## 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):
class Meta:
model = Account
fields = ('id', 'account_name', 'users', 'created')
depth = 1
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.
## 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.
2012-09-01 23:26:27 +04:00
## 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.
2012-10-09 20:49:04 +04:00
class AccountSerializer(serializers.ModelSerializer):
2013-02-24 02:01:29 +04:00
url = serializers.CharField(source='get_absolute_url', read_only=True)
groups = serializers.PrimaryKeyRelatedField(many=True)
2012-09-01 23:26:27 +04:00
class Meta:
model = Account
2012-10-21 18:34:07 +04:00
Extra fields can correspond to any property or callable on the model.
2012-09-01 23:26:27 +04:00
## Relational fields
2013-02-24 02:01:29 +04:00
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.
2012-09-01 23:26:27 +04:00
2013-02-24 02:01:29 +04:00
Alternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation.
2012-09-01 23:26:27 +04:00
2013-02-24 02:01:29 +04:00
For full details see the [serializer relations][relations] documentation.
2012-09-01 23:26:27 +04:00
2013-05-05 19:48:12 +04:00
---
2012-09-01 23:26:27 +04:00
2013-05-05 19:48:12 +04:00
# HyperlinkedModelSerializer
2012-09-01 23:26:27 +04:00
2013-05-05 19:48:12 +04:00
The `HyperlinkedModelSerializer` class is similar to the `ModelSerializer` class except that it uses hyperlinks to represent relationships, rather than primary keys.
2012-09-01 23:26:27 +04:00
2013-05-05 19:48:12 +04:00
By default the serializer will include a `url` field instead of a primary key field.
2012-09-01 23:26:27 +04:00
2013-05-05 19:48:12 +04:00
The url field will be represented using a `HyperlinkedIdentityField` serializer field, and any relationships on the model will be represented using a `HyperlinkedRelatedField` serializer field.
2012-09-01 23:26:27 +04:00
2013-05-05 19:48:12 +04:00
You can explicitly include the primary key by adding it to the `fields` option, for example:
2012-09-01 23:26:27 +04:00
2013-05-05 19:48:12 +04:00
class AccountSerializer(serializers.HyperlinkedModelSerializer):
2012-09-01 23:26:27 +04:00
class Meta:
model = Account
2013-05-05 19:48:12 +04:00
fields = ('url', 'id', 'account_name', 'users', 'created')
2012-09-01 23:26:27 +04:00
2013-05-05 19:48:12 +04:00
## How hyperlinked views are determined
2012-09-01 23:26:27 +04:00
2013-05-05 19:48:12 +04:00
There needs to be a way of determining which views should be used for hyperlinking to model instances.
2013-05-05 19:48:12 +04:00
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.
2013-05-05 19:48:12 +04:00
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 an field on the model. For example:
class AccountSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Account
2013-05-05 19:48:12 +04:00
fields = ('url', 'account_name', 'users', 'created')
lookup_field = 'slug'
For more specfic requirements such as specifying a different lookup for each field, you'll want to set the fields on the serializer explicitly. For example:
class AccountSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(
view_name='account_detail',
lookup_field='account_name'
)
users = serializers.HyperlinkedRelatedField(
view_name='user-detail',
lookup_field='username',
many=True,
read_only=True
)
class Meta:
model = Account
fields = ('url', 'account_name', 'users', 'created')
---
# 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.
2012-10-29 00:43:43 +04:00
## Customising the default fields
2012-09-01 23:26:27 +04:00
2013-05-05 19:48:12 +04:00
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.
2012-09-01 23:26:27 +04:00
2013-05-05 19:48:12 +04:00
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`.
2012-09-01 23:26:27 +04:00
2012-10-29 00:43:43 +04:00
### get_pk_field
2012-09-01 23:26:27 +04:00
2012-10-29 00:43:43 +04:00
**Signature**: `.get_pk_field(self, model_field)`
2012-09-01 23:26:27 +04:00
2012-10-29 00:43:43 +04:00
Returns the field instance that should be used to represent the pk field.
### get_nested_field
2013-04-30 11:24:33 +04:00
**Signature**: `.get_nested_field(self, model_field, related_model, to_many)`
2012-10-29 00:43:43 +04:00
Returns the field instance that should be used to represent a related field when `depth` is specified as being non-zero.
2013-04-30 11:24:33 +04:00
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.
2012-10-29 00:43:43 +04:00
### get_related_field
2013-04-30 11:24:33 +04:00
**Signature**: `.get_related_field(self, model_field, related_model, to_many)`
2012-09-01 23:26:27 +04:00
2012-10-29 00:43:43 +04:00
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.
2013-04-30 11:24:33 +04:00
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.
2012-10-29 00:43:43 +04:00
### get_field
**Signature**: `.get_field(self, model_field)`
Returns the field instance that should be used for non-relational, non-pk fields.
2013-05-05 19:48:12 +04:00
## Example
2012-10-29 00:43:43 +04:00
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
2012-09-01 23:26:27 +04:00
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
2013-02-24 02:01:29 +04:00
[relations]: relations.md