2013-04-25 15:47:34 +04:00
|
|
|
"""
|
|
|
|
Serializers and ModelSerializers are similar to Forms and ModelForms.
|
|
|
|
Unlike forms, they are not constrained to dealing with HTML output, and
|
|
|
|
form encoded input.
|
|
|
|
|
|
|
|
Serialization in REST framework is a two-phase process:
|
|
|
|
|
|
|
|
1. Serializers marshal between complex types like model instances, and
|
2013-11-11 13:54:30 +04:00
|
|
|
python primitives.
|
|
|
|
2. The process of marshalling between python primitives and request and
|
2013-04-25 15:47:34 +04:00
|
|
|
response content is handled by parsers and renderers.
|
|
|
|
"""
|
2014-12-15 14:55:17 +03:00
|
|
|
from __future__ import unicode_literals
|
2015-06-18 16:38:29 +03:00
|
|
|
|
2016-11-01 13:27:11 +03:00
|
|
|
import copy
|
|
|
|
import inspect
|
2016-08-19 16:42:13 +03:00
|
|
|
import traceback
|
2018-09-11 07:12:32 +03:00
|
|
|
from collections import OrderedDict
|
2015-08-27 20:09:08 +03:00
|
|
|
|
2016-11-01 13:27:11 +03:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2018-02-14 23:12:14 +03:00
|
|
|
from django.core.exceptions import ValidationError as DjangoValidationError
|
2012-10-02 19:16:49 +04:00
|
|
|
from django.db import models
|
2016-02-18 22:35:45 +03:00
|
|
|
from django.db.models import DurationField as ModelDurationField
|
2015-06-25 23:55:51 +03:00
|
|
|
from django.db.models.fields import Field as DjangoModelField
|
|
|
|
from django.db.models.fields import FieldDoesNotExist
|
2016-11-01 13:27:11 +03:00
|
|
|
from django.utils import six, timezone
|
2015-05-09 14:37:49 +03:00
|
|
|
from django.utils.functional import cached_property
|
2014-11-03 17:01:02 +03:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
2015-06-18 16:38:29 +03:00
|
|
|
|
2018-09-11 07:12:32 +03:00
|
|
|
from rest_framework.compat import Mapping, postgres_fields, unicode_to_repr
|
2016-11-01 13:27:11 +03:00
|
|
|
from rest_framework.exceptions import ErrorDetail, ValidationError
|
|
|
|
from rest_framework.fields import get_error_detail, set_value
|
|
|
|
from rest_framework.settings import api_settings
|
|
|
|
from rest_framework.utils import html, model_meta, representation
|
2015-06-25 23:55:51 +03:00
|
|
|
from rest_framework.utils.field_mapping import (
|
|
|
|
ClassLookupDict, get_field_kwargs, get_nested_relation_kwargs,
|
|
|
|
get_relation_kwargs, get_url_kwargs
|
2014-09-18 14:20:56 +04:00
|
|
|
)
|
2014-11-07 13:13:46 +03:00
|
|
|
from rest_framework.utils.serializer_helpers import (
|
2017-04-02 03:31:27 +03:00
|
|
|
BindingDict, BoundField, JSONBoundField, NestedBoundField, ReturnDict,
|
|
|
|
ReturnList
|
2015-06-18 16:38:29 +03:00
|
|
|
)
|
2014-10-22 16:30:28 +04:00
|
|
|
from rest_framework.validators import (
|
2014-10-22 19:29:09 +04:00
|
|
|
UniqueForDateValidator, UniqueForMonthValidator, UniqueForYearValidator,
|
|
|
|
UniqueTogetherValidator
|
2014-10-22 16:30:28 +04:00
|
|
|
)
|
2014-12-05 02:29:28 +03:00
|
|
|
|
2012-11-05 14:56:30 +04:00
|
|
|
# Note: We do the following so that users of the framework can use this style:
|
|
|
|
#
|
|
|
|
# example_field = serializers.CharField(...)
|
|
|
|
#
|
2013-05-28 18:09:23 +04:00
|
|
|
# This helps keep the separation between model fields, form fields, and
|
2012-11-05 14:56:30 +04:00
|
|
|
# serializer fields more explicit.
|
2016-11-01 13:27:11 +03:00
|
|
|
from rest_framework.fields import ( # NOQA # isort:skip
|
|
|
|
BooleanField, CharField, ChoiceField, DateField, DateTimeField, DecimalField,
|
|
|
|
DictField, DurationField, EmailField, Field, FileField, FilePathField, FloatField,
|
2018-01-15 17:52:30 +03:00
|
|
|
HiddenField, HStoreField, IPAddressField, ImageField, IntegerField, JSONField,
|
|
|
|
ListField, ModelField, MultipleChoiceField, NullBooleanField, ReadOnlyField,
|
|
|
|
RegexField, SerializerMethodField, SlugField, TimeField, URLField, UUIDField,
|
2016-11-01 13:27:11 +03:00
|
|
|
)
|
|
|
|
from rest_framework.relations import ( # NOQA # isort:skip
|
|
|
|
HyperlinkedIdentityField, HyperlinkedRelatedField, ManyRelatedField,
|
|
|
|
PrimaryKeyRelatedField, RelatedField, SlugRelatedField, StringRelatedField,
|
|
|
|
)
|
2012-11-05 14:56:30 +04:00
|
|
|
|
2016-11-01 13:27:11 +03:00
|
|
|
# Non-field imports, but public API
|
|
|
|
from rest_framework.fields import ( # NOQA # isort:skip
|
|
|
|
CreateOnlyDefault, CurrentUserDefault, SkipField, empty
|
|
|
|
)
|
|
|
|
from rest_framework.relations import Hyperlink, PKOnlyObject # NOQA # isort:skip
|
2014-11-14 00:11:13 +03:00
|
|
|
|
|
|
|
# We assume that 'validators' are intended for the child serializer,
|
|
|
|
# rather than the parent serializer.
|
2014-11-05 18:23:13 +03:00
|
|
|
LIST_SERIALIZER_KWARGS = (
|
|
|
|
'read_only', 'write_only', 'required', 'default', 'initial', 'source',
|
2015-07-16 15:51:15 +03:00
|
|
|
'label', 'help_text', 'style', 'error_messages', 'allow_empty',
|
2015-03-26 02:51:40 +03:00
|
|
|
'instance', 'data', 'partial', 'context', 'allow_null'
|
2014-11-05 18:23:13 +03:00
|
|
|
)
|
|
|
|
|
2015-08-27 20:09:08 +03:00
|
|
|
ALL_FIELDS = '__all__'
|
|
|
|
|
2012-09-20 16:06:27 +04:00
|
|
|
|
2014-10-02 19:24:24 +04:00
|
|
|
# BaseSerializer
|
|
|
|
# --------------
|
2013-10-02 16:45:35 +04:00
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
class BaseSerializer(Field):
|
2014-09-05 19:29:46 +04:00
|
|
|
"""
|
|
|
|
The BaseSerializer class provides a minimal class which may be used
|
|
|
|
for writing custom serializer implementations.
|
2014-12-17 17:14:51 +03:00
|
|
|
|
|
|
|
Note that we strongly restrict the ordering of operations/properties
|
|
|
|
that may be used on the serializer in order to enforce correct usage.
|
|
|
|
|
|
|
|
In particular, if a `data=` argument is passed then:
|
|
|
|
|
|
|
|
.is_valid() - Available.
|
|
|
|
.initial_data - Available.
|
|
|
|
.validated_data - Only available after calling `is_valid()`
|
|
|
|
.errors - Only available after calling `is_valid()`
|
|
|
|
.data - Only available after calling `is_valid()`
|
|
|
|
|
|
|
|
If a `data=` argument is not passed then:
|
|
|
|
|
|
|
|
.is_valid() - Not available.
|
|
|
|
.initial_data - Not available.
|
|
|
|
.validated_data - Not available.
|
|
|
|
.errors - Not available.
|
|
|
|
.data - Available.
|
2014-09-05 19:29:46 +04:00
|
|
|
"""
|
2014-12-05 02:29:28 +03:00
|
|
|
|
2014-12-17 17:14:51 +03:00
|
|
|
def __init__(self, instance=None, data=empty, **kwargs):
|
2014-08-29 19:46:26 +04:00
|
|
|
self.instance = instance
|
2014-12-17 17:14:51 +03:00
|
|
|
if data is not empty:
|
|
|
|
self.initial_data = data
|
2014-09-26 15:48:20 +04:00
|
|
|
self.partial = kwargs.pop('partial', False)
|
|
|
|
self._context = kwargs.pop('context', {})
|
|
|
|
kwargs.pop('many', None)
|
|
|
|
super(BaseSerializer, self).__init__(**kwargs)
|
|
|
|
|
|
|
|
def __new__(cls, *args, **kwargs):
|
|
|
|
# We override this method in order to automagically create
|
|
|
|
# `ListSerializer` classes instead when `many=True` is set.
|
|
|
|
if kwargs.pop('many', False):
|
2014-11-14 00:11:13 +03:00
|
|
|
return cls.many_init(*args, **kwargs)
|
2014-09-26 15:48:20 +04:00
|
|
|
return super(BaseSerializer, cls).__new__(cls, *args, **kwargs)
|
2013-10-02 16:45:35 +04:00
|
|
|
|
2014-11-14 00:11:13 +03:00
|
|
|
@classmethod
|
|
|
|
def many_init(cls, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
This method implements the creation of a `ListSerializer` parent
|
|
|
|
class when `many=True` is used. You can customize it if you need to
|
|
|
|
control which keyword arguments are passed to the parent, and
|
|
|
|
which are passed to the child.
|
2014-11-25 13:39:58 +03:00
|
|
|
|
|
|
|
Note that we're over-cautious in passing most arguments to both parent
|
|
|
|
and child classes in order to try to cover the general case. If you're
|
|
|
|
overriding this method you'll probably want something much simpler, eg:
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def many_init(cls, *args, **kwargs):
|
|
|
|
kwargs['child'] = cls()
|
|
|
|
return CustomListSerializer(*args, **kwargs)
|
2014-11-14 00:11:13 +03:00
|
|
|
"""
|
2015-09-07 00:02:44 +03:00
|
|
|
allow_empty = kwargs.pop('allow_empty', None)
|
2014-11-14 00:11:13 +03:00
|
|
|
child_serializer = cls(*args, **kwargs)
|
2015-09-03 18:27:33 +03:00
|
|
|
list_kwargs = {
|
|
|
|
'child': child_serializer,
|
|
|
|
}
|
2015-09-07 00:02:44 +03:00
|
|
|
if allow_empty is not None:
|
|
|
|
list_kwargs['allow_empty'] = allow_empty
|
2015-10-17 12:00:11 +03:00
|
|
|
list_kwargs.update({
|
|
|
|
key: value for key, value in kwargs.items()
|
2014-11-14 00:11:13 +03:00
|
|
|
if key in LIST_SERIALIZER_KWARGS
|
2015-10-17 12:00:11 +03:00
|
|
|
})
|
2014-11-28 12:56:44 +03:00
|
|
|
meta = getattr(cls, 'Meta', None)
|
|
|
|
list_serializer_class = getattr(meta, 'list_serializer_class', ListSerializer)
|
|
|
|
return list_serializer_class(*args, **list_kwargs)
|
2014-11-14 00:11:13 +03:00
|
|
|
|
2014-09-12 12:49:35 +04:00
|
|
|
def to_internal_value(self, data):
|
|
|
|
raise NotImplementedError('`to_internal_value()` must be implemented.')
|
2013-04-18 21:28:20 +04:00
|
|
|
|
2014-09-12 12:49:35 +04:00
|
|
|
def to_representation(self, instance):
|
|
|
|
raise NotImplementedError('`to_representation()` must be implemented.')
|
2013-11-08 16:12:40 +04:00
|
|
|
|
2014-09-26 13:46:52 +04:00
|
|
|
def update(self, instance, validated_data):
|
2014-09-05 19:29:46 +04:00
|
|
|
raise NotImplementedError('`update()` must be implemented.')
|
2013-03-12 22:35:20 +04:00
|
|
|
|
2014-09-26 13:46:52 +04:00
|
|
|
def create(self, validated_data):
|
2014-09-05 19:29:46 +04:00
|
|
|
raise NotImplementedError('`create()` must be implemented.')
|
2013-03-12 22:35:20 +04:00
|
|
|
|
2014-10-03 16:42:06 +04:00
|
|
|
def save(self, **kwargs):
|
2014-11-18 17:49:00 +03:00
|
|
|
assert not hasattr(self, 'save_object'), (
|
|
|
|
'Serializer `%s.%s` has old-style version 2 `.save_object()` '
|
|
|
|
'that is no longer compatible with REST framework 3. '
|
|
|
|
'Use the new-style `.create()` and `.update()` methods instead.' %
|
|
|
|
(self.__class__.__module__, self.__class__.__name__)
|
|
|
|
)
|
|
|
|
|
2014-12-02 12:27:40 +03:00
|
|
|
assert hasattr(self, '_errors'), (
|
|
|
|
'You must call `.is_valid()` before calling `.save()`.'
|
|
|
|
)
|
|
|
|
|
|
|
|
assert not self.errors, (
|
|
|
|
'You cannot call `.save()` on a serializer with invalid data.'
|
|
|
|
)
|
|
|
|
|
2015-07-17 14:39:22 +03:00
|
|
|
# Guard against incorrect use of `serializer.save(commit=False)`
|
|
|
|
assert 'commit' not in kwargs, (
|
|
|
|
"'commit' is not a valid keyword argument to the 'save()' method. "
|
|
|
|
"If you need to access data before committing to the database then "
|
|
|
|
"inspect 'serializer.validated_data' instead. "
|
|
|
|
"You can also pass additional keyword arguments to 'save()' if you "
|
|
|
|
"need to set extra attributes on the saved model instance. "
|
|
|
|
"For example: 'serializer.save(owner=request.user)'.'"
|
|
|
|
)
|
|
|
|
|
2015-09-22 21:49:51 +03:00
|
|
|
assert not hasattr(self, '_data'), (
|
|
|
|
"You cannot call `.save()` after accessing `serializer.data`."
|
|
|
|
"If you need to access data before committing to the database then "
|
|
|
|
"inspect 'serializer.validated_data' instead. "
|
|
|
|
)
|
|
|
|
|
2014-11-06 13:34:59 +03:00
|
|
|
validated_data = dict(
|
|
|
|
list(self.validated_data.items()) +
|
|
|
|
list(kwargs.items())
|
|
|
|
)
|
2013-03-12 22:35:20 +04:00
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
if self.instance is not None:
|
2014-10-08 15:17:30 +04:00
|
|
|
self.instance = self.update(self.instance, validated_data)
|
|
|
|
assert self.instance is not None, (
|
|
|
|
'`update()` did not return an object instance.'
|
|
|
|
)
|
2013-03-13 07:59:25 +04:00
|
|
|
else:
|
2014-09-26 13:46:52 +04:00
|
|
|
self.instance = self.create(validated_data)
|
2014-09-26 14:56:29 +04:00
|
|
|
assert self.instance is not None, (
|
|
|
|
'`create()` did not return an object instance.'
|
|
|
|
)
|
2013-03-12 17:33:02 +04:00
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
return self.instance
|
2013-03-12 17:33:02 +04:00
|
|
|
|
2014-09-05 19:29:46 +04:00
|
|
|
def is_valid(self, raise_exception=False):
|
2014-10-17 16:23:14 +04:00
|
|
|
assert not hasattr(self, 'restore_object'), (
|
2014-10-22 13:32:32 +04:00
|
|
|
'Serializer `%s.%s` has old-style version 2 `.restore_object()` '
|
2014-10-17 16:23:14 +04:00
|
|
|
'that is no longer compatible with REST framework 3. '
|
|
|
|
'Use the new-style `.create()` and `.update()` methods instead.' %
|
2014-10-22 13:32:32 +04:00
|
|
|
(self.__class__.__module__, self.__class__.__name__)
|
2014-10-17 16:23:14 +04:00
|
|
|
)
|
|
|
|
|
2014-12-17 17:14:51 +03:00
|
|
|
assert hasattr(self, 'initial_data'), (
|
2015-02-03 03:14:34 +03:00
|
|
|
'Cannot call `.is_valid()` as no `data=` keyword argument was '
|
2014-12-17 17:14:51 +03:00
|
|
|
'passed when instantiating the serializer instance.'
|
|
|
|
)
|
|
|
|
|
2014-09-05 19:29:46 +04:00
|
|
|
if not hasattr(self, '_validated_data'):
|
|
|
|
try:
|
2014-12-17 17:14:51 +03:00
|
|
|
self._validated_data = self.run_validation(self.initial_data)
|
2014-10-17 16:23:14 +04:00
|
|
|
except ValidationError as exc:
|
2014-09-05 19:29:46 +04:00
|
|
|
self._validated_data = {}
|
2014-10-10 17:16:09 +04:00
|
|
|
self._errors = exc.detail
|
2014-09-05 19:29:46 +04:00
|
|
|
else:
|
|
|
|
self._errors = {}
|
|
|
|
|
|
|
|
if self._errors and raise_exception:
|
2015-07-23 16:31:25 +03:00
|
|
|
raise ValidationError(self.errors)
|
2014-09-05 19:29:46 +04:00
|
|
|
|
|
|
|
return not bool(self._errors)
|
2012-09-20 16:06:27 +04:00
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
@property
|
|
|
|
def data(self):
|
2014-12-17 17:14:51 +03:00
|
|
|
if hasattr(self, 'initial_data') and not hasattr(self, '_validated_data'):
|
|
|
|
msg = (
|
|
|
|
'When a serializer is passed a `data` keyword argument you '
|
|
|
|
'must call `.is_valid()` before attempting to access the '
|
|
|
|
'serialized `.data` representation.\n'
|
|
|
|
'You should either call `.is_valid()` first, '
|
|
|
|
'or access `.initial_data` instead.'
|
|
|
|
)
|
|
|
|
raise AssertionError(msg)
|
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
if not hasattr(self, '_data'):
|
2014-10-15 18:13:28 +04:00
|
|
|
if self.instance is not None and not getattr(self, '_errors', None):
|
2014-09-12 12:49:35 +04:00
|
|
|
self._data = self.to_representation(self.instance)
|
2014-10-17 16:23:14 +04:00
|
|
|
elif hasattr(self, '_validated_data') and not getattr(self, '_errors', None):
|
|
|
|
self._data = self.to_representation(self.validated_data)
|
2014-08-29 19:46:26 +04:00
|
|
|
else:
|
|
|
|
self._data = self.get_initial()
|
|
|
|
return self._data
|
2012-09-20 16:06:27 +04:00
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
@property
|
|
|
|
def errors(self):
|
|
|
|
if not hasattr(self, '_errors'):
|
|
|
|
msg = 'You must call `.is_valid()` before accessing `.errors`.'
|
|
|
|
raise AssertionError(msg)
|
|
|
|
return self._errors
|
2012-09-20 16:06:27 +04:00
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
@property
|
|
|
|
def validated_data(self):
|
|
|
|
if not hasattr(self, '_validated_data'):
|
|
|
|
msg = 'You must call `.is_valid()` before accessing `.validated_data`.'
|
|
|
|
raise AssertionError(msg)
|
|
|
|
return self._validated_data
|
2012-09-20 16:06:27 +04:00
|
|
|
|
|
|
|
|
2014-10-02 19:24:24 +04:00
|
|
|
# Serializer & ListSerializer classes
|
|
|
|
# -----------------------------------
|
|
|
|
|
|
|
|
class SerializerMetaclass(type):
|
|
|
|
"""
|
2015-01-05 18:04:01 +03:00
|
|
|
This metaclass sets a dictionary named `_declared_fields` on the class.
|
2014-10-02 19:24:24 +04:00
|
|
|
|
|
|
|
Any instances of `Field` included as attributes on either the class
|
|
|
|
or on any of its superclasses will be include in the
|
2015-01-05 18:04:01 +03:00
|
|
|
`_declared_fields` dictionary.
|
2014-10-02 19:24:24 +04:00
|
|
|
"""
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _get_declared_fields(cls, bases, attrs):
|
|
|
|
fields = [(field_name, attrs.pop(field_name))
|
|
|
|
for field_name, obj in list(attrs.items())
|
|
|
|
if isinstance(obj, Field)]
|
|
|
|
fields.sort(key=lambda x: x[1]._creation_counter)
|
|
|
|
|
|
|
|
# If this class is subclassing another Serializer, add that Serializer's
|
|
|
|
# fields. Note that we loop over the bases in *reverse*. This is necessary
|
|
|
|
# in order to maintain the correct order of fields.
|
2015-01-21 16:03:37 +03:00
|
|
|
for base in reversed(bases):
|
2014-10-02 19:24:24 +04:00
|
|
|
if hasattr(base, '_declared_fields'):
|
2017-01-04 00:14:19 +03:00
|
|
|
fields = [
|
|
|
|
(field_name, obj) for field_name, obj
|
|
|
|
in base._declared_fields.items()
|
|
|
|
if field_name not in attrs
|
|
|
|
] + fields
|
2014-10-02 19:24:24 +04:00
|
|
|
|
2014-11-06 15:00:30 +03:00
|
|
|
return OrderedDict(fields)
|
2014-10-02 19:24:24 +04:00
|
|
|
|
|
|
|
def __new__(cls, name, bases, attrs):
|
|
|
|
attrs['_declared_fields'] = cls._get_declared_fields(bases, attrs)
|
|
|
|
return super(SerializerMetaclass, cls).__new__(cls, name, bases, attrs)
|
|
|
|
|
|
|
|
|
2016-10-11 12:25:21 +03:00
|
|
|
def as_serializer_error(exc):
|
2014-12-08 17:56:45 +03:00
|
|
|
assert isinstance(exc, (ValidationError, DjangoValidationError))
|
|
|
|
|
|
|
|
if isinstance(exc, DjangoValidationError):
|
2016-10-11 12:25:21 +03:00
|
|
|
detail = get_error_detail(exc)
|
|
|
|
else:
|
|
|
|
detail = exc.detail
|
|
|
|
|
2017-02-20 00:00:41 +03:00
|
|
|
if isinstance(detail, Mapping):
|
2014-12-08 17:56:45 +03:00
|
|
|
# If errors may be a dict we use the standard {key: list of values}.
|
|
|
|
# Here we ensure that all the values are *lists* of errors.
|
2015-10-17 12:00:11 +03:00
|
|
|
return {
|
2017-02-20 00:00:41 +03:00
|
|
|
key: value if isinstance(value, (list, Mapping)) else [value]
|
2016-10-11 12:25:21 +03:00
|
|
|
for key, value in detail.items()
|
2015-10-17 12:00:11 +03:00
|
|
|
}
|
2016-10-11 12:25:21 +03:00
|
|
|
elif isinstance(detail, list):
|
2014-12-08 17:56:45 +03:00
|
|
|
# Errors raised as a list are non-field errors.
|
|
|
|
return {
|
2016-10-11 12:25:21 +03:00
|
|
|
api_settings.NON_FIELD_ERRORS_KEY: detail
|
2014-12-08 17:56:45 +03:00
|
|
|
}
|
|
|
|
# Errors raised as a string are non-field errors.
|
|
|
|
return {
|
2016-10-11 12:25:21 +03:00
|
|
|
api_settings.NON_FIELD_ERRORS_KEY: [detail]
|
2014-12-08 17:56:45 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
@six.add_metaclass(SerializerMetaclass)
|
|
|
|
class Serializer(BaseSerializer):
|
2014-11-03 17:01:02 +03:00
|
|
|
default_error_messages = {
|
|
|
|
'invalid': _('Invalid data. Expected a dictionary, but got {datatype}.')
|
|
|
|
}
|
|
|
|
|
2014-10-31 19:38:39 +03:00
|
|
|
@property
|
|
|
|
def fields(self):
|
2014-11-07 13:13:46 +03:00
|
|
|
"""
|
|
|
|
A dictionary of {field_name: field_instance}.
|
|
|
|
"""
|
2014-12-05 02:29:28 +03:00
|
|
|
# `fields` is evaluated lazily. We do this to ensure that we don't
|
2014-11-07 13:13:46 +03:00
|
|
|
# have issues importing modules that use ModelSerializers as fields,
|
|
|
|
# even if Django's app-loading stage has not yet run.
|
2014-10-31 19:38:39 +03:00
|
|
|
if not hasattr(self, '_fields'):
|
|
|
|
self._fields = BindingDict(self)
|
|
|
|
for key, value in self.get_fields().items():
|
|
|
|
self._fields[key] = value
|
|
|
|
return self._fields
|
|
|
|
|
2015-05-09 14:37:49 +03:00
|
|
|
@cached_property
|
2015-05-17 09:54:33 +03:00
|
|
|
def _writable_fields(self):
|
2015-05-09 14:37:49 +03:00
|
|
|
return [
|
2018-03-20 23:09:31 +03:00
|
|
|
field for field in self.fields.values() if not field.read_only
|
2015-05-09 14:37:49 +03:00
|
|
|
]
|
|
|
|
|
|
|
|
@cached_property
|
2015-05-17 09:54:33 +03:00
|
|
|
def _readable_fields(self):
|
2015-06-20 08:51:03 +03:00
|
|
|
return [
|
|
|
|
field for field in self.fields.values()
|
|
|
|
if not field.write_only
|
|
|
|
]
|
2015-05-09 14:37:49 +03:00
|
|
|
|
2014-10-31 19:38:39 +03:00
|
|
|
def get_fields(self):
|
2014-11-07 13:13:46 +03:00
|
|
|
"""
|
|
|
|
Returns a dictionary of {field_name: field_instance}.
|
|
|
|
"""
|
2014-08-29 19:46:26 +04:00
|
|
|
# Every new serializer is created with a clone of the field instances.
|
|
|
|
# This allows users to dynamically modify the fields on a serializer
|
2017-11-27 11:08:18 +03:00
|
|
|
# instance without affecting every other serializer instance.
|
2014-09-18 14:20:56 +04:00
|
|
|
return copy.deepcopy(self._declared_fields)
|
2012-09-20 16:06:27 +04:00
|
|
|
|
2014-10-31 19:38:39 +03:00
|
|
|
def get_validators(self):
|
2014-11-07 13:13:46 +03:00
|
|
|
"""
|
|
|
|
Returns a list of validator callables.
|
|
|
|
"""
|
|
|
|
# Used by the lazily-evaluated `validators` property.
|
2014-12-19 18:50:29 +03:00
|
|
|
meta = getattr(self, 'Meta', None)
|
|
|
|
validators = getattr(meta, 'validators', None)
|
2019-02-19 18:38:20 +03:00
|
|
|
return list(validators) if validators else []
|
2014-10-31 19:38:39 +03:00
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
def get_initial(self):
|
2014-12-17 17:14:51 +03:00
|
|
|
if hasattr(self, 'initial_data'):
|
2017-12-04 10:39:55 +03:00
|
|
|
# initial_data may not be a valid type
|
|
|
|
if not isinstance(self.initial_data, Mapping):
|
|
|
|
return OrderedDict()
|
|
|
|
|
2014-11-14 02:05:44 +03:00
|
|
|
return OrderedDict([
|
2014-12-17 17:14:51 +03:00
|
|
|
(field_name, field.get_value(self.initial_data))
|
2014-11-07 17:13:50 +03:00
|
|
|
for field_name, field in self.fields.items()
|
2015-02-17 13:58:00 +03:00
|
|
|
if (field.get_value(self.initial_data) is not empty) and
|
|
|
|
not field.read_only
|
2014-11-14 02:05:44 +03:00
|
|
|
])
|
2014-10-02 19:24:24 +04:00
|
|
|
|
2014-11-14 02:05:44 +03:00
|
|
|
return OrderedDict([
|
2014-09-10 19:57:22 +04:00
|
|
|
(field.field_name, field.get_initial())
|
2014-08-29 19:46:26 +04:00
|
|
|
for field in self.fields.values()
|
2014-11-07 18:38:27 +03:00
|
|
|
if not field.read_only
|
2014-11-14 02:05:44 +03:00
|
|
|
])
|
2012-10-24 12:28:10 +04:00
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
def get_value(self, dictionary):
|
|
|
|
# We override the default field access in order to support
|
|
|
|
# nested HTML forms.
|
|
|
|
if html.is_html_input(dictionary):
|
2015-07-03 19:28:48 +03:00
|
|
|
return html.parse_html_dict(dictionary, prefix=self.field_name) or empty
|
2014-08-29 19:46:26 +04:00
|
|
|
return dictionary.get(self.field_name, empty)
|
2012-10-24 14:39:17 +04:00
|
|
|
|
2014-09-29 14:23:02 +04:00
|
|
|
def run_validation(self, data=empty):
|
2012-09-20 16:06:27 +04:00
|
|
|
"""
|
2014-09-29 14:23:02 +04:00
|
|
|
We override the default `run_validation`, because the validation
|
|
|
|
performed by validators and the `.validate()` method should
|
|
|
|
be coerced into an error dictionary with a 'non_fields_error' key.
|
2012-09-20 16:06:27 +04:00
|
|
|
"""
|
2014-12-08 17:56:45 +03:00
|
|
|
(is_empty_value, data) = self.validate_empty_values(data)
|
|
|
|
if is_empty_value:
|
|
|
|
return data
|
2014-09-05 19:29:46 +04:00
|
|
|
|
2014-09-29 14:23:02 +04:00
|
|
|
value = self.to_internal_value(data)
|
|
|
|
try:
|
|
|
|
self.run_validators(value)
|
2014-10-08 15:36:28 +04:00
|
|
|
value = self.validate(value)
|
|
|
|
assert value is not None, '.validate() should return the validated data'
|
2014-12-08 17:56:45 +03:00
|
|
|
except (ValidationError, DjangoValidationError) as exc:
|
2016-10-11 12:25:21 +03:00
|
|
|
raise ValidationError(detail=as_serializer_error(exc))
|
2014-10-22 13:32:32 +04:00
|
|
|
|
2014-09-29 14:23:02 +04:00
|
|
|
return value
|
|
|
|
|
2018-04-06 16:20:54 +03:00
|
|
|
def _read_only_defaults(self):
|
|
|
|
fields = [
|
|
|
|
field for field in self.fields.values()
|
|
|
|
if (field.read_only) and (field.default != empty) and (field.source != '*') and ('.' not in field.source)
|
|
|
|
]
|
|
|
|
|
|
|
|
defaults = OrderedDict()
|
|
|
|
for field in fields:
|
|
|
|
try:
|
|
|
|
default = field.get_default()
|
|
|
|
except SkipField:
|
|
|
|
continue
|
|
|
|
defaults[field.field_name] = default
|
|
|
|
|
|
|
|
return defaults
|
|
|
|
|
|
|
|
def run_validators(self, value):
|
|
|
|
"""
|
|
|
|
Add read_only fields with defaults to value before running validators.
|
|
|
|
"""
|
2019-01-08 14:39:30 +03:00
|
|
|
if isinstance(value, dict):
|
|
|
|
to_validate = self._read_only_defaults()
|
|
|
|
to_validate.update(value)
|
|
|
|
else:
|
|
|
|
to_validate = value
|
2018-04-06 16:20:54 +03:00
|
|
|
super(Serializer, self).run_validators(to_validate)
|
|
|
|
|
2014-09-29 14:23:02 +04:00
|
|
|
def to_internal_value(self, data):
|
|
|
|
"""
|
|
|
|
Dict of native values <- Dict of primitive datatypes.
|
|
|
|
"""
|
2017-02-20 00:00:41 +03:00
|
|
|
if not isinstance(data, Mapping):
|
2014-12-08 17:56:45 +03:00
|
|
|
message = self.error_messages['invalid'].format(
|
|
|
|
datatype=type(data).__name__
|
|
|
|
)
|
|
|
|
raise ValidationError({
|
|
|
|
api_settings.NON_FIELD_ERRORS_KEY: [message]
|
2016-10-11 12:25:21 +03:00
|
|
|
}, code='invalid')
|
2014-12-08 17:56:45 +03:00
|
|
|
|
2014-11-14 02:05:44 +03:00
|
|
|
ret = OrderedDict()
|
|
|
|
errors = OrderedDict()
|
2015-05-17 09:54:33 +03:00
|
|
|
fields = self._writable_fields
|
2012-09-20 16:06:27 +04:00
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
for field in fields:
|
2014-09-05 19:29:46 +04:00
|
|
|
validate_method = getattr(self, 'validate_' + field.field_name, None)
|
2014-08-29 19:46:26 +04:00
|
|
|
primitive_value = field.get_value(data)
|
|
|
|
try:
|
2014-09-12 12:49:35 +04:00
|
|
|
validated_value = field.run_validation(primitive_value)
|
2014-09-05 19:29:46 +04:00
|
|
|
if validate_method is not None:
|
|
|
|
validated_value = validate_method(validated_value)
|
2014-10-17 16:23:14 +04:00
|
|
|
except ValidationError as exc:
|
2014-10-10 17:16:09 +04:00
|
|
|
errors[field.field_name] = exc.detail
|
2014-12-01 13:48:45 +03:00
|
|
|
except DjangoValidationError as exc:
|
2016-10-11 12:25:21 +03:00
|
|
|
errors[field.field_name] = get_error_detail(exc)
|
2014-08-29 19:46:26 +04:00
|
|
|
except SkipField:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
set_value(ret, field.source_attrs, validated_value)
|
2013-01-31 21:06:23 +04:00
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
if errors:
|
2014-10-17 16:23:14 +04:00
|
|
|
raise ValidationError(errors)
|
2013-10-02 19:13:34 +04:00
|
|
|
|
2014-09-29 14:23:02 +04:00
|
|
|
return ret
|
2012-09-20 16:06:27 +04:00
|
|
|
|
2014-09-12 12:49:35 +04:00
|
|
|
def to_representation(self, instance):
|
2012-10-22 18:12:25 +04:00
|
|
|
"""
|
2014-08-29 19:46:26 +04:00
|
|
|
Object instance -> Dict of primitive datatypes.
|
2012-10-22 18:12:25 +04:00
|
|
|
"""
|
2014-11-14 02:05:44 +03:00
|
|
|
ret = OrderedDict()
|
2015-05-17 09:54:33 +03:00
|
|
|
fields = self._readable_fields
|
2014-01-14 15:25:44 +04:00
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
for field in fields:
|
2015-01-05 17:32:12 +03:00
|
|
|
try:
|
|
|
|
attribute = field.get_attribute(instance)
|
|
|
|
except SkipField:
|
|
|
|
continue
|
|
|
|
|
2016-03-13 22:39:19 +03:00
|
|
|
# We skip `to_representation` for `None` values so that fields do
|
|
|
|
# not have to explicitly deal with that case.
|
|
|
|
#
|
|
|
|
# For related fields with `use_pk_only_optimization` we need to
|
|
|
|
# resolve the pk value.
|
|
|
|
check_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else attribute
|
|
|
|
if check_for_none is None:
|
2014-11-27 19:40:58 +03:00
|
|
|
ret[field.field_name] = None
|
2014-10-16 23:45:36 +04:00
|
|
|
else:
|
2014-11-27 19:40:58 +03:00
|
|
|
ret[field.field_name] = field.to_representation(attribute)
|
2013-01-27 00:54:03 +04:00
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
return ret
|
2012-11-20 13:41:36 +04:00
|
|
|
|
2014-09-02 20:41:23 +04:00
|
|
|
def validate(self, attrs):
|
|
|
|
return attrs
|
|
|
|
|
2014-10-09 18:11:19 +04:00
|
|
|
def __repr__(self):
|
2014-12-15 14:55:17 +03:00
|
|
|
return unicode_to_repr(representation.serializer_repr(self, indent=1))
|
2014-10-09 18:11:19 +04:00
|
|
|
|
|
|
|
# The following are used for accessing `BoundField` instances on the
|
|
|
|
# serializer, for the purposes of presenting a form-like API onto the
|
|
|
|
# field values and field errors.
|
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
def __iter__(self):
|
|
|
|
for field in self.fields.values():
|
2014-10-09 18:11:19 +04:00
|
|
|
yield self[field.field_name]
|
2012-10-22 18:12:25 +04:00
|
|
|
|
2014-10-09 18:11:19 +04:00
|
|
|
def __getitem__(self, key):
|
|
|
|
field = self.fields[key]
|
|
|
|
value = self.data.get(key)
|
|
|
|
error = self.errors.get(key) if hasattr(self, '_errors') else None
|
2014-10-10 17:16:09 +04:00
|
|
|
if isinstance(field, Serializer):
|
|
|
|
return NestedBoundField(field, value, error)
|
2017-04-02 03:31:27 +03:00
|
|
|
if isinstance(field, JSONField):
|
|
|
|
return JSONBoundField(field, value, error)
|
2014-10-09 18:11:19 +04:00
|
|
|
return BoundField(field, value, error)
|
2014-09-09 20:46:28 +04:00
|
|
|
|
2014-11-14 02:05:44 +03:00
|
|
|
# Include a backlink to the serializer class on return objects.
|
|
|
|
# Allows renderers such as HTMLFormRenderer to get the full field info.
|
|
|
|
|
|
|
|
@property
|
|
|
|
def data(self):
|
|
|
|
ret = super(Serializer, self).data
|
|
|
|
return ReturnDict(ret, serializer=self)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def errors(self):
|
|
|
|
ret = super(Serializer, self).errors
|
2016-10-21 17:21:23 +03:00
|
|
|
if isinstance(ret, list) and len(ret) == 1 and getattr(ret[0], 'code', None) == 'null':
|
2016-10-12 12:47:17 +03:00
|
|
|
# Edge case. Provide a more descriptive error than
|
|
|
|
# "this field may not be null", when no data is passed.
|
|
|
|
detail = ErrorDetail('No data provided', code='null')
|
|
|
|
ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]}
|
2014-11-14 02:05:44 +03:00
|
|
|
return ReturnDict(ret, serializer=self)
|
|
|
|
|
2012-12-29 17:19:05 +04:00
|
|
|
|
2014-09-26 16:08:20 +04:00
|
|
|
# There's some replication of `ListField` here,
|
|
|
|
# but that's probably better than obfuscating the call hierarchy.
|
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
class ListSerializer(BaseSerializer):
|
|
|
|
child = None
|
2014-10-02 19:24:24 +04:00
|
|
|
many = True
|
2013-03-12 17:33:02 +04:00
|
|
|
|
2014-11-06 13:34:59 +03:00
|
|
|
default_error_messages = {
|
2015-07-16 15:51:15 +03:00
|
|
|
'not_a_list': _('Expected a list of items but got type "{input_type}".'),
|
|
|
|
'empty': _('This list may not be empty.')
|
2014-11-06 13:34:59 +03:00
|
|
|
}
|
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
self.child = kwargs.pop('child', copy.deepcopy(self.child))
|
2015-07-16 15:51:15 +03:00
|
|
|
self.allow_empty = kwargs.pop('allow_empty', True)
|
2014-08-29 19:46:26 +04:00
|
|
|
assert self.child is not None, '`child` is a required argument.'
|
2014-09-19 19:43:13 +04:00
|
|
|
assert not inspect.isclass(self.child), '`child` has not been instantiated.'
|
2014-08-29 19:46:26 +04:00
|
|
|
super(ListSerializer, self).__init__(*args, **kwargs)
|
2014-09-25 14:40:32 +04:00
|
|
|
self.child.bind(field_name='', parent=self)
|
2013-03-22 21:01:06 +04:00
|
|
|
|
2016-06-24 15:04:18 +03:00
|
|
|
def bind(self, field_name, parent):
|
|
|
|
super(ListSerializer, self).bind(field_name, parent)
|
|
|
|
self.partial = self.parent.partial
|
|
|
|
|
2014-10-02 19:24:24 +04:00
|
|
|
def get_initial(self):
|
2014-12-17 17:14:51 +03:00
|
|
|
if hasattr(self, 'initial_data'):
|
|
|
|
return self.to_representation(self.initial_data)
|
2014-11-14 02:05:44 +03:00
|
|
|
return []
|
2014-10-02 19:24:24 +04:00
|
|
|
|
2014-08-29 19:46:26 +04:00
|
|
|
def get_value(self, dictionary):
|
2014-11-07 13:51:08 +03:00
|
|
|
"""
|
|
|
|
Given the input dictionary, return the field value.
|
|
|
|
"""
|
2014-08-29 19:46:26 +04:00
|
|
|
# We override the default field access in order to support
|
|
|
|
# lists in HTML forms.
|
2014-09-26 16:08:20 +04:00
|
|
|
if html.is_html_input(dictionary):
|
2018-04-20 16:11:52 +03:00
|
|
|
return html.parse_html_list(dictionary, prefix=self.field_name, default=empty)
|
2014-08-29 19:46:26 +04:00
|
|
|
return dictionary.get(self.field_name, empty)
|
2013-03-19 18:26:48 +04:00
|
|
|
|
2014-12-08 17:56:45 +03:00
|
|
|
def run_validation(self, data=empty):
|
|
|
|
"""
|
|
|
|
We override the default `run_validation`, because the validation
|
|
|
|
performed by validators and the `.validate()` method should
|
|
|
|
be coerced into an error dictionary with a 'non_fields_error' key.
|
|
|
|
"""
|
|
|
|
(is_empty_value, data) = self.validate_empty_values(data)
|
|
|
|
if is_empty_value:
|
|
|
|
return data
|
|
|
|
|
|
|
|
value = self.to_internal_value(data)
|
|
|
|
try:
|
|
|
|
self.run_validators(value)
|
|
|
|
value = self.validate(value)
|
|
|
|
assert value is not None, '.validate() should return the validated data'
|
|
|
|
except (ValidationError, DjangoValidationError) as exc:
|
2016-10-11 12:25:21 +03:00
|
|
|
raise ValidationError(detail=as_serializer_error(exc))
|
2014-12-08 17:56:45 +03:00
|
|
|
|
|
|
|
return value
|
|
|
|
|
2014-09-12 12:49:35 +04:00
|
|
|
def to_internal_value(self, data):
|
2012-09-20 16:06:27 +04:00
|
|
|
"""
|
2014-08-29 19:46:26 +04:00
|
|
|
List of dicts of native values <- List of dicts of primitive datatypes.
|
2012-09-20 16:06:27 +04:00
|
|
|
"""
|
2014-08-29 19:46:26 +04:00
|
|
|
if html.is_html_input(data):
|
2018-04-20 16:11:52 +03:00
|
|
|
data = html.parse_html_list(data, default=[])
|
2014-11-06 13:34:59 +03:00
|
|
|
|
|
|
|
if not isinstance(data, list):
|
|
|
|
message = self.error_messages['not_a_list'].format(
|
|
|
|
input_type=type(data).__name__
|
|
|
|
)
|
|
|
|
raise ValidationError({
|
|
|
|
api_settings.NON_FIELD_ERRORS_KEY: [message]
|
2016-10-11 12:25:21 +03:00
|
|
|
}, code='not_a_list')
|
2014-11-06 13:34:59 +03:00
|
|
|
|
2015-07-16 15:51:15 +03:00
|
|
|
if not self.allow_empty and len(data) == 0:
|
2016-06-29 09:48:31 +03:00
|
|
|
if self.parent and self.partial:
|
2016-06-24 15:04:18 +03:00
|
|
|
raise SkipField()
|
|
|
|
|
2015-07-16 15:51:15 +03:00
|
|
|
message = self.error_messages['empty']
|
|
|
|
raise ValidationError({
|
|
|
|
api_settings.NON_FIELD_ERRORS_KEY: [message]
|
2016-10-11 12:25:21 +03:00
|
|
|
}, code='empty')
|
2015-07-16 15:51:15 +03:00
|
|
|
|
2014-11-06 13:34:59 +03:00
|
|
|
ret = []
|
2014-11-14 02:05:44 +03:00
|
|
|
errors = []
|
2014-11-06 13:34:59 +03:00
|
|
|
|
|
|
|
for item in data:
|
|
|
|
try:
|
|
|
|
validated = self.child.run_validation(item)
|
2014-11-06 14:35:34 +03:00
|
|
|
except ValidationError as exc:
|
2014-11-06 13:34:59 +03:00
|
|
|
errors.append(exc.detail)
|
|
|
|
else:
|
|
|
|
ret.append(validated)
|
|
|
|
errors.append({})
|
|
|
|
|
|
|
|
if any(errors):
|
|
|
|
raise ValidationError(errors)
|
|
|
|
|
|
|
|
return ret
|
2012-09-20 16:06:27 +04:00
|
|
|
|
2014-09-12 12:49:35 +04:00
|
|
|
def to_representation(self, data):
|
2013-01-31 00:38:11 +04:00
|
|
|
"""
|
2014-08-29 19:46:26 +04:00
|
|
|
List of object instances -> List of dicts of primitive datatypes.
|
2013-01-31 00:38:11 +04:00
|
|
|
"""
|
2014-12-10 12:13:15 +03:00
|
|
|
# Dealing with nested relationships, data can be a Manager,
|
2014-12-10 11:19:27 +03:00
|
|
|
# so, first get a queryset from the Manager if needed
|
2015-06-25 05:02:28 +03:00
|
|
|
iterable = data.all() if isinstance(data, models.Manager) else data
|
|
|
|
|
2014-11-14 02:05:44 +03:00
|
|
|
return [
|
2014-12-09 19:49:07 +03:00
|
|
|
self.child.to_representation(item) for item in iterable
|
2014-11-14 02:05:44 +03:00
|
|
|
]
|
2013-01-31 21:06:23 +04:00
|
|
|
|
2014-12-08 17:56:45 +03:00
|
|
|
def validate(self, attrs):
|
|
|
|
return attrs
|
|
|
|
|
2014-11-13 23:24:48 +03:00
|
|
|
def update(self, instance, validated_data):
|
|
|
|
raise NotImplementedError(
|
|
|
|
"Serializers with many=True do not support multiple update by "
|
|
|
|
"default, only multiple create. For updates it is unclear how to "
|
|
|
|
"deal with insertions and deletions. If you need to support "
|
|
|
|
"multiple update, use a `ListSerializer` class and override "
|
|
|
|
"`.update()` so you can specify the behavior exactly."
|
|
|
|
)
|
|
|
|
|
|
|
|
def create(self, validated_data):
|
|
|
|
return [
|
|
|
|
self.child.create(attrs) for attrs in validated_data
|
|
|
|
]
|
|
|
|
|
2014-11-06 13:34:59 +03:00
|
|
|
def save(self, **kwargs):
|
2014-11-07 13:51:08 +03:00
|
|
|
"""
|
|
|
|
Save and return a list of object instances.
|
|
|
|
"""
|
2015-07-17 14:39:22 +03:00
|
|
|
# Guard against incorrect use of `serializer.save(commit=False)`
|
|
|
|
assert 'commit' not in kwargs, (
|
|
|
|
"'commit' is not a valid keyword argument to the 'save()' method. "
|
|
|
|
"If you need to access data before committing to the database then "
|
|
|
|
"inspect 'serializer.validated_data' instead. "
|
|
|
|
"You can also pass additional keyword arguments to 'save()' if you "
|
|
|
|
"need to set extra attributes on the saved model instance. "
|
|
|
|
"For example: 'serializer.save(owner=request.user)'.'"
|
|
|
|
)
|
|
|
|
|
2014-11-06 13:34:59 +03:00
|
|
|
validated_data = [
|
|
|
|
dict(list(attrs.items()) + list(kwargs.items()))
|
|
|
|
for attrs in self.validated_data
|
|
|
|
]
|
|
|
|
|
2014-11-13 23:24:48 +03:00
|
|
|
if self.instance is not None:
|
|
|
|
self.instance = self.update(self.instance, validated_data)
|
|
|
|
assert self.instance is not None, (
|
|
|
|
'`update()` did not return an object instance.'
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
self.instance = self.create(validated_data)
|
|
|
|
assert self.instance is not None, (
|
|
|
|
'`create()` did not return an object instance.'
|
|
|
|
)
|
2014-11-06 13:34:59 +03:00
|
|
|
|
|
|
|
return self.instance
|
2013-01-31 21:06:23 +04:00
|
|
|
|
2016-06-08 17:55:09 +03:00
|
|
|
def is_valid(self, raise_exception=False):
|
|
|
|
# This implementation is the same as the default,
|
|
|
|
# except that we use lists, rather than dicts, as the empty case.
|
|
|
|
assert hasattr(self, 'initial_data'), (
|
|
|
|
'Cannot call `.is_valid()` as no `data=` keyword argument was '
|
|
|
|
'passed when instantiating the serializer instance.'
|
|
|
|
)
|
|
|
|
|
|
|
|
if not hasattr(self, '_validated_data'):
|
|
|
|
try:
|
|
|
|
self._validated_data = self.run_validation(self.initial_data)
|
|
|
|
except ValidationError as exc:
|
|
|
|
self._validated_data = []
|
|
|
|
self._errors = exc.detail
|
|
|
|
else:
|
|
|
|
self._errors = []
|
|
|
|
|
|
|
|
if self._errors and raise_exception:
|
|
|
|
raise ValidationError(self.errors)
|
|
|
|
|
|
|
|
return not bool(self._errors)
|
|
|
|
|
2014-09-09 20:46:28 +04:00
|
|
|
def __repr__(self):
|
2014-12-15 14:55:17 +03:00
|
|
|
return unicode_to_repr(representation.list_repr(self, indent=1))
|
2012-09-20 16:06:27 +04:00
|
|
|
|
2014-11-14 02:05:44 +03:00
|
|
|
# Include a backlink to the serializer class on return objects.
|
|
|
|
# Allows renderers such as HTMLFormRenderer to get the full field info.
|
|
|
|
|
|
|
|
@property
|
|
|
|
def data(self):
|
|
|
|
ret = super(ListSerializer, self).data
|
|
|
|
return ReturnList(ret, serializer=self)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def errors(self):
|
|
|
|
ret = super(ListSerializer, self).errors
|
2016-10-21 17:21:23 +03:00
|
|
|
if isinstance(ret, list) and len(ret) == 1 and getattr(ret[0], 'code', None) == 'null':
|
2016-10-12 12:47:17 +03:00
|
|
|
# Edge case. Provide a more descriptive error than
|
|
|
|
# "this field may not be null", when no data is passed.
|
|
|
|
detail = ErrorDetail('No data provided', code='null')
|
|
|
|
ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]}
|
2014-11-14 02:05:44 +03:00
|
|
|
if isinstance(ret, dict):
|
|
|
|
return ReturnDict(ret, serializer=self)
|
|
|
|
return ReturnList(ret, serializer=self)
|
|
|
|
|
2012-09-20 16:06:27 +04:00
|
|
|
|
2014-10-02 19:24:24 +04:00
|
|
|
# ModelSerializer & HyperlinkedModelSerializer
|
|
|
|
# --------------------------------------------
|
|
|
|
|
2014-12-07 14:12:40 +03:00
|
|
|
def raise_errors_on_nested_writes(method_name, serializer, validated_data):
|
2014-12-05 16:50:28 +03:00
|
|
|
"""
|
|
|
|
Give explicit errors when users attempt to pass writable nested data.
|
|
|
|
|
|
|
|
If we don't do this explicitly they'd get a less helpful error when
|
|
|
|
calling `.save()` on the serializer.
|
|
|
|
|
2015-02-02 11:50:54 +03:00
|
|
|
We don't *automatically* support these sorts of nested writes because
|
2014-12-05 16:50:28 +03:00
|
|
|
there are too many ambiguities to define a default behavior.
|
|
|
|
|
|
|
|
Eg. Suppose we have a `UserSerializer` with a nested profile. How should
|
2015-02-02 11:50:54 +03:00
|
|
|
we handle the case of an update, where the `profile` relationship does
|
2014-12-05 16:50:28 +03:00
|
|
|
not exist? Any of the following might be valid:
|
|
|
|
|
|
|
|
* Raise an application error.
|
|
|
|
* Silently ignore the nested part of the update.
|
|
|
|
* Automatically create a profile instance.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Ensure we don't have a writable nested field. For example:
|
|
|
|
#
|
|
|
|
# class UserSerializer(ModelSerializer):
|
|
|
|
# ...
|
|
|
|
# profile = ProfileSerializer()
|
|
|
|
assert not any(
|
2015-02-17 13:58:00 +03:00
|
|
|
isinstance(field, BaseSerializer) and
|
2016-10-12 18:51:01 +03:00
|
|
|
(field.source in validated_data) and
|
|
|
|
isinstance(validated_data[field.source], (list, dict))
|
2016-11-10 19:36:56 +03:00
|
|
|
for field in serializer._writable_fields
|
2014-12-05 16:50:28 +03:00
|
|
|
), (
|
2016-02-11 21:09:21 +03:00
|
|
|
'The `.{method_name}()` method does not support writable nested '
|
2014-12-05 16:58:39 +03:00
|
|
|
'fields by default.\nWrite an explicit `.{method_name}()` method for '
|
2014-12-05 16:50:28 +03:00
|
|
|
'serializer `{module}.{class_name}`, or set `read_only=True` on '
|
|
|
|
'nested serializer fields.'.format(
|
|
|
|
method_name=method_name,
|
|
|
|
module=serializer.__class__.__module__,
|
|
|
|
class_name=serializer.__class__.__name__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
# Ensure we don't have a writable dotted-source field. For example:
|
|
|
|
#
|
|
|
|
# class UserSerializer(ModelSerializer):
|
|
|
|
# ...
|
|
|
|
# address = serializer.CharField('profile.address')
|
|
|
|
assert not any(
|
2015-02-17 13:58:00 +03:00
|
|
|
'.' in field.source and
|
|
|
|
(key in validated_data) and
|
|
|
|
isinstance(validated_data[key], (list, dict))
|
2014-12-05 16:50:28 +03:00
|
|
|
for key, field in serializer.fields.items()
|
|
|
|
), (
|
|
|
|
'The `.{method_name}()` method does not support writable dotted-source '
|
2014-12-05 16:58:39 +03:00
|
|
|
'fields by default.\nWrite an explicit `.{method_name}()` method for '
|
2014-12-05 16:50:28 +03:00
|
|
|
'serializer `{module}.{class_name}`, or set `read_only=True` on '
|
|
|
|
'dotted-source serializer fields.'.format(
|
|
|
|
method_name=method_name,
|
|
|
|
module=serializer.__class__.__module__,
|
|
|
|
class_name=serializer.__class__.__name__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2012-10-04 16:28:14 +04:00
|
|
|
class ModelSerializer(Serializer):
|
2014-11-07 13:13:46 +03:00
|
|
|
"""
|
|
|
|
A `ModelSerializer` is just a regular `Serializer`, except that:
|
|
|
|
|
|
|
|
* A set of default fields are automatically populated.
|
|
|
|
* A set of default validators are automatically populated.
|
|
|
|
* Default `.create()` and `.update()` implementations are provided.
|
2014-12-01 14:37:38 +03:00
|
|
|
|
|
|
|
The process of automatically determining a set of serializer fields
|
|
|
|
based on the model fields is reasonably complex, but you almost certainly
|
2014-12-05 02:29:28 +03:00
|
|
|
don't need to dig into the implementation.
|
2014-12-01 14:37:38 +03:00
|
|
|
|
|
|
|
If the `ModelSerializer` class *doesn't* generate the set of fields that
|
|
|
|
you need you should either declare the extra/differing fields explicitly on
|
|
|
|
the serializer class, or simply use a `Serializer` class.
|
2014-11-07 13:13:46 +03:00
|
|
|
"""
|
2014-12-19 18:35:52 +03:00
|
|
|
serializer_field_mapping = {
|
2013-02-28 17:41:42 +04:00
|
|
|
models.AutoField: IntegerField,
|
2014-09-09 20:46:28 +04:00
|
|
|
models.BigIntegerField: IntegerField,
|
|
|
|
models.BooleanField: BooleanField,
|
|
|
|
models.CharField: CharField,
|
|
|
|
models.CommaSeparatedIntegerField: CharField,
|
|
|
|
models.DateField: DateField,
|
|
|
|
models.DateTimeField: DateTimeField,
|
|
|
|
models.DecimalField: DecimalField,
|
|
|
|
models.EmailField: EmailField,
|
2014-09-11 23:22:32 +04:00
|
|
|
models.Field: ModelField,
|
2014-09-09 20:46:28 +04:00
|
|
|
models.FileField: FileField,
|
|
|
|
models.FloatField: FloatField,
|
2014-09-10 11:53:33 +04:00
|
|
|
models.ImageField: ImageField,
|
2013-02-28 17:41:42 +04:00
|
|
|
models.IntegerField: IntegerField,
|
2014-09-23 17:30:17 +04:00
|
|
|
models.NullBooleanField: NullBooleanField,
|
2013-02-28 17:41:42 +04:00
|
|
|
models.PositiveIntegerField: IntegerField,
|
|
|
|
models.PositiveSmallIntegerField: IntegerField,
|
2014-09-09 20:46:28 +04:00
|
|
|
models.SlugField: SlugField,
|
|
|
|
models.SmallIntegerField: IntegerField,
|
|
|
|
models.TextField: CharField,
|
2014-09-02 20:41:23 +04:00
|
|
|
models.TimeField: TimeField,
|
2015-02-28 10:18:47 +03:00
|
|
|
models.URLField: URLField,
|
|
|
|
models.GenericIPAddressField: IPAddressField,
|
2015-07-19 00:26:03 +03:00
|
|
|
models.FilePathField: FilePathField,
|
2014-12-19 18:35:52 +03:00
|
|
|
}
|
2015-06-01 19:20:53 +03:00
|
|
|
if ModelDurationField is not None:
|
|
|
|
serializer_field_mapping[ModelDurationField] = DurationField
|
2015-02-06 18:45:02 +03:00
|
|
|
serializer_related_field = PrimaryKeyRelatedField
|
2015-10-21 15:32:16 +03:00
|
|
|
serializer_related_to_field = SlugRelatedField
|
2015-02-06 18:45:02 +03:00
|
|
|
serializer_url_field = HyperlinkedIdentityField
|
|
|
|
serializer_choice_field = ChoiceField
|
2014-08-29 19:46:26 +04:00
|
|
|
|
2015-07-14 13:21:33 +03:00
|
|
|
# The field name for hyperlinked identity fields. Defaults to 'url'.
|
|
|
|
# You can modify this using the API setting.
|
|
|
|
#
|
|
|
|
# Note that if you instead need modify this on a per-serializer basis,
|
|
|
|
# you'll also need to ensure you update the `create` method on any generic
|
|
|
|
# views, to correctly handle the 'Location' response header for
|
|
|
|
# "HTTP 201 Created" responses.
|
2015-09-03 18:24:13 +03:00
|
|
|
url_field_name = None
|
2014-08-29 19:46:26 +04:00
|
|
|
|
2015-07-14 13:21:33 +03:00
|
|
|
# Default `create` and `update` behavior...
|
2014-12-04 01:52:35 +03:00
|
|
|
def create(self, validated_data):
|
2014-12-01 14:59:04 +03:00
|
|
|
"""
|
|
|
|
We have a bit of extra checking around this in order to provide
|
|
|
|
descriptive messages when something goes wrong, but this method is
|
|
|
|
essentially just:
|
|
|
|
|
2014-12-04 01:52:35 +03:00
|
|
|
return ExampleModel.objects.create(**validated_data)
|
2014-12-01 14:59:04 +03:00
|
|
|
|
|
|
|
If there are many to many fields present on the instance then they
|
|
|
|
cannot be set until the model is instantiated, in which case the
|
|
|
|
implementation is like so:
|
|
|
|
|
2014-12-04 01:52:35 +03:00
|
|
|
example_relationship = validated_data.pop('example_relationship')
|
|
|
|
instance = ExampleModel.objects.create(**validated_data)
|
2014-12-01 14:59:04 +03:00
|
|
|
instance.example_relationship = example_relationship
|
|
|
|
return instance
|
|
|
|
|
|
|
|
The default implementation also does not handle nested relationships.
|
|
|
|
If you want to support writable nested relationships you'll need
|
|
|
|
to write an explicit `.create()` method.
|
|
|
|
"""
|
2014-12-07 14:12:40 +03:00
|
|
|
raise_errors_on_nested_writes('create', self, validated_data)
|
2014-10-16 23:45:18 +04:00
|
|
|
|
2014-09-18 14:20:56 +04:00
|
|
|
ModelClass = self.Meta.model
|
2014-09-18 17:58:08 +04:00
|
|
|
|
2014-12-04 01:52:35 +03:00
|
|
|
# Remove many-to-many relationships from validated_data.
|
2014-09-18 17:58:08 +04:00
|
|
|
# They are not valid arguments to the default `.create()` method,
|
|
|
|
# as they require that the instance has already been saved.
|
|
|
|
info = model_meta.get_field_info(ModelClass)
|
|
|
|
many_to_many = {}
|
2014-09-18 18:47:27 +04:00
|
|
|
for field_name, relation_info in info.relations.items():
|
2014-12-04 01:52:35 +03:00
|
|
|
if relation_info.to_many and (field_name in validated_data):
|
|
|
|
many_to_many[field_name] = validated_data.pop(field_name)
|
2014-09-18 17:58:08 +04:00
|
|
|
|
2014-11-15 17:23:58 +03:00
|
|
|
try:
|
2018-08-06 15:30:43 +03:00
|
|
|
instance = ModelClass._default_manager.create(**validated_data)
|
2016-08-19 16:42:13 +03:00
|
|
|
except TypeError:
|
|
|
|
tb = traceback.format_exc()
|
2014-11-15 17:23:58 +03:00
|
|
|
msg = (
|
2018-08-06 21:11:55 +03:00
|
|
|
'Got a `TypeError` when calling `%s.%s.create()`. '
|
2014-12-02 16:04:49 +03:00
|
|
|
'This may be because you have a writable field on the '
|
|
|
|
'serializer class that is not a valid argument to '
|
2018-08-06 21:11:55 +03:00
|
|
|
'`%s.%s.create()`. You may need to make the field '
|
2014-12-02 16:04:49 +03:00
|
|
|
'read-only, or override the %s.create() method to handle '
|
2016-08-19 16:42:13 +03:00
|
|
|
'this correctly.\nOriginal exception was:\n %s' %
|
2014-12-02 16:04:49 +03:00
|
|
|
(
|
|
|
|
ModelClass.__name__,
|
2018-08-06 21:11:55 +03:00
|
|
|
ModelClass._default_manager.name,
|
2014-12-02 16:04:49 +03:00
|
|
|
ModelClass.__name__,
|
2018-08-06 21:11:55 +03:00
|
|
|
ModelClass._default_manager.name,
|
2014-12-02 16:04:49 +03:00
|
|
|
self.__class__.__name__,
|
2016-08-19 16:42:13 +03:00
|
|
|
tb
|
2014-12-02 16:04:49 +03:00
|
|
|
)
|
|
|
|
)
|
|
|
|
raise TypeError(msg)
|
2014-09-18 17:58:08 +04:00
|
|
|
|
2014-09-18 18:47:27 +04:00
|
|
|
# Save many-to-many relationships after the instance is created.
|
2014-09-18 17:58:08 +04:00
|
|
|
if many_to_many:
|
2014-09-18 18:47:27 +04:00
|
|
|
for field_name, value in many_to_many.items():
|
2017-10-05 21:41:38 +03:00
|
|
|
field = getattr(instance, field_name)
|
|
|
|
field.set(value)
|
2014-09-18 17:58:08 +04:00
|
|
|
|
|
|
|
return instance
|
2014-09-02 20:41:23 +04:00
|
|
|
|
2014-12-04 01:52:35 +03:00
|
|
|
def update(self, instance, validated_data):
|
2014-12-07 14:12:40 +03:00
|
|
|
raise_errors_on_nested_writes('update', self, validated_data)
|
2016-10-10 15:03:46 +03:00
|
|
|
info = model_meta.get_field_info(instance)
|
2014-10-16 23:45:18 +04:00
|
|
|
|
2015-07-14 14:22:51 +03:00
|
|
|
# Simply set each attribute on the instance, and then save it.
|
|
|
|
# Note that unlike `.create()` we don't need to treat many-to-many
|
|
|
|
# relationships as being a special case. During updates we already
|
|
|
|
# have an instance pk for the relationships to be associated with.
|
2014-12-04 01:52:35 +03:00
|
|
|
for attr, value in validated_data.items():
|
2016-10-10 15:03:46 +03:00
|
|
|
if attr in info.relations and info.relations[attr].to_many:
|
2017-10-05 21:41:38 +03:00
|
|
|
field = getattr(instance, attr)
|
|
|
|
field.set(value)
|
2016-10-10 15:03:46 +03:00
|
|
|
else:
|
|
|
|
setattr(instance, attr, value)
|
2014-10-08 15:17:30 +04:00
|
|
|
instance.save()
|
2014-12-05 16:58:39 +03:00
|
|
|
|
2014-10-08 15:17:30 +04:00
|
|
|
return instance
|
2014-09-02 20:41:23 +04:00
|
|
|
|
2014-12-19 17:51:45 +03:00
|
|
|
# Determine the fields to apply...
|
2014-12-01 14:59:04 +03:00
|
|
|
|
2014-10-31 19:38:39 +03:00
|
|
|
def get_fields(self):
|
2014-12-19 18:35:52 +03:00
|
|
|
"""
|
|
|
|
Return the dict of field names -> field instances that should be
|
|
|
|
used for `self.fields` when instantiating the serializer.
|
|
|
|
"""
|
2015-09-03 18:24:13 +03:00
|
|
|
if self.url_field_name is None:
|
|
|
|
self.url_field_name = api_settings.URL_FIELD_NAME
|
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
assert hasattr(self, 'Meta'), (
|
|
|
|
'Class {serializer_class} missing "Meta" attribute'.format(
|
|
|
|
serializer_class=self.__class__.__name__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
assert hasattr(self.Meta, 'model'), (
|
|
|
|
'Class {serializer_class} missing "Meta.model" attribute'.format(
|
|
|
|
serializer_class=self.__class__.__name__
|
|
|
|
)
|
|
|
|
)
|
2015-03-23 18:01:19 +03:00
|
|
|
if model_meta.is_abstract_model(self.Meta.model):
|
|
|
|
raise ValueError(
|
|
|
|
'Cannot use ModelSerializer with Abstract Models.'
|
|
|
|
)
|
2014-09-29 14:23:02 +04:00
|
|
|
|
2014-09-18 14:20:56 +04:00
|
|
|
declared_fields = copy.deepcopy(self._declared_fields)
|
|
|
|
model = getattr(self.Meta, 'model')
|
|
|
|
depth = getattr(self.Meta, 'depth', 0)
|
2014-09-29 14:23:02 +04:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
if depth is not None:
|
|
|
|
assert depth >= 0, "'depth' may not be negative."
|
|
|
|
assert depth <= 10, "'depth' may not be greater than 10."
|
2014-10-22 16:30:28 +04:00
|
|
|
|
2014-09-18 14:20:56 +04:00
|
|
|
# Retrieve metadata about fields & relationships on the model class.
|
|
|
|
info = model_meta.get_field_info(model)
|
2014-12-19 16:13:20 +03:00
|
|
|
field_names = self.get_field_names(declared_fields, info)
|
2014-10-22 19:29:09 +04:00
|
|
|
|
2014-12-19 17:51:45 +03:00
|
|
|
# Determine any extra field arguments and hidden fields that
|
|
|
|
# should be included
|
|
|
|
extra_kwargs = self.get_extra_kwargs()
|
|
|
|
extra_kwargs, hidden_fields = self.get_uniqueness_extra_kwargs(
|
|
|
|
field_names, declared_fields, extra_kwargs
|
|
|
|
)
|
2014-10-22 19:29:09 +04:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
# Determine the fields that should be included on the serializer.
|
|
|
|
fields = OrderedDict()
|
2014-09-29 14:23:02 +04:00
|
|
|
|
2014-12-19 16:13:20 +03:00
|
|
|
for field_name in field_names:
|
2014-12-20 00:32:43 +03:00
|
|
|
# If the field is explicitly declared on the class then use that.
|
2014-09-18 14:20:56 +04:00
|
|
|
if field_name in declared_fields:
|
2014-12-20 00:32:43 +03:00
|
|
|
fields[field_name] = declared_fields[field_name]
|
2014-09-18 14:20:56 +04:00
|
|
|
continue
|
2014-08-29 19:46:26 +04:00
|
|
|
|
2016-11-17 19:51:22 +03:00
|
|
|
extra_field_kwargs = extra_kwargs.get(field_name, {})
|
2017-09-04 13:47:53 +03:00
|
|
|
source = extra_field_kwargs.get('source', '*')
|
|
|
|
if source == '*':
|
|
|
|
source = field_name
|
2016-11-17 19:51:22 +03:00
|
|
|
|
2014-12-19 18:09:57 +03:00
|
|
|
# Determine the serializer field class and keyword arguments.
|
2014-12-20 00:32:43 +03:00
|
|
|
field_class, field_kwargs = self.build_field(
|
2016-11-17 19:51:22 +03:00
|
|
|
source, info, model, depth
|
2014-12-20 00:32:43 +03:00
|
|
|
)
|
2014-09-18 15:17:21 +04:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
# Include any kwargs defined in `Meta.extra_kwargs`
|
2015-02-06 19:15:10 +03:00
|
|
|
field_kwargs = self.include_extra_kwargs(
|
|
|
|
field_kwargs, extra_field_kwargs
|
2014-12-20 00:32:43 +03:00
|
|
|
)
|
2014-09-18 15:17:21 +04:00
|
|
|
|
|
|
|
# Create the serializer field.
|
2014-12-20 00:32:43 +03:00
|
|
|
fields[field_name] = field_class(**field_kwargs)
|
2014-05-22 23:51:20 +04:00
|
|
|
|
2014-12-19 18:09:57 +03:00
|
|
|
# Add in any hidden fields.
|
2014-12-20 00:32:43 +03:00
|
|
|
fields.update(hidden_fields)
|
2014-10-28 19:21:49 +03:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
return fields
|
2012-09-20 16:06:27 +04:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
# Methods for determining the set of field names to include...
|
|
|
|
|
|
|
|
def get_field_names(self, declared_fields, info):
|
|
|
|
"""
|
|
|
|
Returns the list of all field names that should be created when
|
|
|
|
instantiating this serializer class. This is based on the default
|
|
|
|
set of fields, but also takes into account the `Meta.fields` or
|
|
|
|
`Meta.exclude` options if they have been specified.
|
|
|
|
"""
|
2014-09-18 14:20:56 +04:00
|
|
|
fields = getattr(self.Meta, 'fields', None)
|
2014-10-10 17:16:09 +04:00
|
|
|
exclude = getattr(self.Meta, 'exclude', None)
|
2014-09-18 14:20:56 +04:00
|
|
|
|
2015-08-27 20:09:08 +03:00
|
|
|
if fields and fields != ALL_FIELDS and not isinstance(fields, (list, tuple)):
|
2014-12-05 17:15:58 +03:00
|
|
|
raise TypeError(
|
2015-09-28 12:57:14 +03:00
|
|
|
'The `fields` option must be a list or tuple or "__all__". '
|
|
|
|
'Got %s.' % type(fields).__name__
|
2014-12-05 17:15:58 +03:00
|
|
|
)
|
2014-12-05 09:50:53 +03:00
|
|
|
|
|
|
|
if exclude and not isinstance(exclude, (list, tuple)):
|
2014-12-05 17:15:58 +03:00
|
|
|
raise TypeError(
|
|
|
|
'The `exclude` option must be a list or tuple. Got %s.' %
|
|
|
|
type(exclude).__name__
|
|
|
|
)
|
2014-12-05 09:50:53 +03:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
assert not (fields and exclude), (
|
|
|
|
"Cannot set both 'fields' and 'exclude' options on "
|
|
|
|
"serializer {serializer_class}.".format(
|
|
|
|
serializer_class=self.__class__.__name__
|
|
|
|
)
|
|
|
|
)
|
2014-10-08 19:09:37 +04:00
|
|
|
|
2016-10-10 15:03:46 +03:00
|
|
|
assert not (fields is None and exclude is None), (
|
|
|
|
"Creating a ModelSerializer without either the 'fields' attribute "
|
|
|
|
"or the 'exclude' attribute has been deprecated since 3.3.0, "
|
|
|
|
"and is now disallowed. Add an explicit fields = '__all__' to the "
|
|
|
|
"{serializer_class} serializer.".format(
|
|
|
|
serializer_class=self.__class__.__name__
|
|
|
|
),
|
|
|
|
)
|
2015-08-27 20:09:08 +03:00
|
|
|
|
|
|
|
if fields == ALL_FIELDS:
|
|
|
|
fields = None
|
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
if fields is not None:
|
|
|
|
# Ensure that all declared fields have also been included in the
|
|
|
|
# `Meta.fields` option.
|
2014-09-18 14:20:56 +04:00
|
|
|
|
2018-02-21 18:39:53 +03:00
|
|
|
# Do not require any fields that are declared in a parent class,
|
2015-01-21 16:12:14 +03:00
|
|
|
# in order to allow serializer subclasses to only include
|
|
|
|
# a subset of fields.
|
|
|
|
required_field_names = set(declared_fields)
|
|
|
|
for cls in self.__class__.__bases__:
|
|
|
|
required_field_names -= set(getattr(cls, '_declared_fields', []))
|
|
|
|
|
|
|
|
for field_name in required_field_names:
|
2014-12-19 18:35:52 +03:00
|
|
|
assert field_name in fields, (
|
|
|
|
"The field '{field_name}' was declared on serializer "
|
|
|
|
"{serializer_class}, but has not been included in the "
|
|
|
|
"'fields' option.".format(
|
|
|
|
field_name=field_name,
|
|
|
|
serializer_class=self.__class__.__name__
|
2014-12-18 18:03:15 +03:00
|
|
|
)
|
2014-12-19 18:35:52 +03:00
|
|
|
)
|
|
|
|
return fields
|
|
|
|
|
|
|
|
# Use the default set of field names if `Meta.fields` is not specified.
|
|
|
|
fields = self.get_default_field_names(declared_fields, info)
|
|
|
|
|
|
|
|
if exclude is not None:
|
|
|
|
# If `Meta.exclude` is included, then remove those fields.
|
|
|
|
for field_name in exclude:
|
2017-11-20 11:51:16 +03:00
|
|
|
assert field_name not in self._declared_fields, (
|
|
|
|
"Cannot both declare the field '{field_name}' and include "
|
|
|
|
"it in the {serializer_class} 'exclude' option. Remove the "
|
|
|
|
"field or, if inherited from a parent serializer, disable "
|
|
|
|
"with `{field_name} = None`."
|
|
|
|
.format(
|
|
|
|
field_name=field_name,
|
|
|
|
serializer_class=self.__class__.__name__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
assert field_name in fields, (
|
2015-05-30 18:57:35 +03:00
|
|
|
"The field '{field_name}' was included on serializer "
|
2014-12-19 18:35:52 +03:00
|
|
|
"{serializer_class} in the 'exclude' option, but does "
|
|
|
|
"not match any model field.".format(
|
|
|
|
field_name=field_name,
|
|
|
|
serializer_class=self.__class__.__name__
|
|
|
|
)
|
|
|
|
)
|
|
|
|
fields.remove(field_name)
|
2015-01-21 16:03:37 +03:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
return fields
|
2015-01-21 16:03:37 +03:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
def get_default_field_names(self, declared_fields, model_info):
|
|
|
|
"""
|
|
|
|
Return the default list of field names that will be used if the
|
|
|
|
`Meta.fields` option is not specified.
|
|
|
|
"""
|
|
|
|
return (
|
|
|
|
[model_info.pk.name] +
|
2018-01-08 12:49:46 +03:00
|
|
|
list(declared_fields) +
|
|
|
|
list(model_info.fields) +
|
|
|
|
list(model_info.forward_relations)
|
2014-12-19 18:35:52 +03:00
|
|
|
)
|
2014-09-18 14:20:56 +04:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
# Methods for constructing serializer fields...
|
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
def build_field(self, field_name, info, model_class, nested_depth):
|
2014-12-19 18:35:52 +03:00
|
|
|
"""
|
|
|
|
Return a two tuple of (cls, kwargs) to build a serializer field with.
|
|
|
|
"""
|
2014-12-19 18:09:57 +03:00
|
|
|
if field_name in info.fields_and_pk:
|
2014-12-20 00:32:43 +03:00
|
|
|
model_field = info.fields_and_pk[field_name]
|
|
|
|
return self.build_standard_field(field_name, model_field)
|
2014-12-19 18:09:57 +03:00
|
|
|
|
|
|
|
elif field_name in info.relations:
|
2014-12-20 00:32:43 +03:00
|
|
|
relation_info = info.relations[field_name]
|
2014-12-19 18:35:52 +03:00
|
|
|
if not nested_depth:
|
2014-12-20 00:32:43 +03:00
|
|
|
return self.build_relational_field(field_name, relation_info)
|
2014-10-28 19:21:49 +03:00
|
|
|
else:
|
2014-12-20 00:32:43 +03:00
|
|
|
return self.build_nested_field(field_name, relation_info, nested_depth)
|
2014-10-28 19:21:49 +03:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
elif hasattr(model_class, field_name):
|
|
|
|
return self.build_property_field(field_name, model_class)
|
2014-11-19 16:55:10 +03:00
|
|
|
|
2015-07-14 13:21:33 +03:00
|
|
|
elif field_name == self.url_field_name:
|
2014-12-20 00:32:43 +03:00
|
|
|
return self.build_url_field(field_name, model_class)
|
2014-10-28 19:21:49 +03:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
return self.build_unknown_field(field_name, model_class)
|
2015-01-21 21:29:40 +03:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
def build_standard_field(self, field_name, model_field):
|
2014-12-19 18:35:52 +03:00
|
|
|
"""
|
|
|
|
Create regular model fields.
|
|
|
|
"""
|
|
|
|
field_mapping = ClassLookupDict(self.serializer_field_mapping)
|
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
field_class = field_mapping[model_field]
|
|
|
|
field_kwargs = get_field_kwargs(field_name, model_field)
|
2014-12-19 18:35:52 +03:00
|
|
|
|
2017-05-30 20:57:45 +03:00
|
|
|
# Special case to handle when a OneToOneField is also the primary key
|
|
|
|
if model_field.one_to_one and model_field.primary_key:
|
|
|
|
field_class = self.serializer_related_field
|
|
|
|
field_kwargs['queryset'] = model_field.related_model.objects
|
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
if 'choices' in field_kwargs:
|
2014-12-19 18:35:52 +03:00
|
|
|
# Fields with choices get coerced into `ChoiceField`
|
|
|
|
# instead of using their regular typed field.
|
2015-02-06 18:45:02 +03:00
|
|
|
field_class = self.serializer_choice_field
|
2015-07-16 17:46:27 +03:00
|
|
|
# Some model fields may introduce kwargs that would not be valid
|
|
|
|
# for the choice field. We need to strip these out.
|
|
|
|
# Eg. models.DecimalField(max_digits=3, decimal_places=1, choices=DECIMAL_CHOICES)
|
2017-11-06 12:03:01 +03:00
|
|
|
valid_kwargs = {
|
2015-07-16 17:46:27 +03:00
|
|
|
'read_only', 'write_only',
|
|
|
|
'required', 'default', 'initial', 'source',
|
|
|
|
'label', 'help_text', 'style',
|
|
|
|
'error_messages', 'validators', 'allow_null', 'allow_blank',
|
|
|
|
'choices'
|
2017-11-06 12:03:01 +03:00
|
|
|
}
|
2018-01-08 12:49:46 +03:00
|
|
|
for key in list(field_kwargs):
|
2015-07-16 17:46:27 +03:00
|
|
|
if key not in valid_kwargs:
|
|
|
|
field_kwargs.pop(key)
|
2015-02-05 06:33:59 +03:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
if not issubclass(field_class, ModelField):
|
2014-12-19 18:35:52 +03:00
|
|
|
# `model_field` is only valid for the fallback case of
|
|
|
|
# `ModelField`, which is used when no other typed field
|
|
|
|
# matched to the model field.
|
2014-12-20 00:32:43 +03:00
|
|
|
field_kwargs.pop('model_field', None)
|
2015-02-05 06:33:59 +03:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
if not issubclass(field_class, CharField) and not issubclass(field_class, ChoiceField):
|
2014-12-19 18:35:52 +03:00
|
|
|
# `allow_blank` is only valid for textual fields.
|
2014-12-20 00:32:43 +03:00
|
|
|
field_kwargs.pop('allow_blank', None)
|
2014-12-19 18:35:52 +03:00
|
|
|
|
2015-02-05 06:33:59 +03:00
|
|
|
if postgres_fields and isinstance(model_field, postgres_fields.ArrayField):
|
2015-02-06 18:45:02 +03:00
|
|
|
# Populate the `child` argument on `ListField` instances generated
|
2017-01-08 16:36:49 +03:00
|
|
|
# for the PostgreSQL specific `ArrayField`.
|
2015-02-05 17:12:14 +03:00
|
|
|
child_model_field = model_field.base_field
|
2015-02-05 06:33:59 +03:00
|
|
|
child_field_class, child_field_kwargs = self.build_standard_field(
|
|
|
|
'child', child_model_field
|
|
|
|
)
|
|
|
|
field_kwargs['child'] = child_field_class(**child_field_kwargs)
|
2014-11-19 17:51:49 +03:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
return field_class, field_kwargs
|
2014-11-19 16:55:10 +03:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
def build_relational_field(self, field_name, relation_info):
|
2014-12-19 18:35:52 +03:00
|
|
|
"""
|
|
|
|
Create fields for forward and reverse relationships.
|
|
|
|
"""
|
2015-02-06 18:45:02 +03:00
|
|
|
field_class = self.serializer_related_field
|
2014-12-20 00:32:43 +03:00
|
|
|
field_kwargs = get_relation_kwargs(field_name, relation_info)
|
2014-11-19 16:55:10 +03:00
|
|
|
|
2015-10-21 15:32:16 +03:00
|
|
|
to_field = field_kwargs.pop('to_field', None)
|
2016-10-13 14:43:43 +03:00
|
|
|
if to_field and not relation_info.reverse and not relation_info.related_model._meta.get_field(to_field).primary_key:
|
2015-10-21 15:32:16 +03:00
|
|
|
field_kwargs['slug_field'] = to_field
|
|
|
|
field_class = self.serializer_related_to_field
|
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
# `view_name` is only valid for hyperlinked relationships.
|
2014-12-20 00:32:43 +03:00
|
|
|
if not issubclass(field_class, HyperlinkedRelatedField):
|
|
|
|
field_kwargs.pop('view_name', None)
|
2014-11-19 16:55:10 +03:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
return field_class, field_kwargs
|
2014-11-19 16:55:10 +03:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
def build_nested_field(self, field_name, relation_info, nested_depth):
|
2014-12-19 18:35:52 +03:00
|
|
|
"""
|
|
|
|
Create nested fields for forward and reverse relationships.
|
|
|
|
"""
|
|
|
|
class NestedSerializer(ModelSerializer):
|
|
|
|
class Meta:
|
2014-12-20 00:32:43 +03:00
|
|
|
model = relation_info.related_model
|
2015-04-06 07:13:25 +03:00
|
|
|
depth = nested_depth - 1
|
2016-06-02 16:39:10 +03:00
|
|
|
fields = '__all__'
|
2014-10-28 19:21:49 +03:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
field_class = NestedSerializer
|
|
|
|
field_kwargs = get_nested_relation_kwargs(relation_info)
|
2014-09-18 14:20:56 +04:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
return field_class, field_kwargs
|
2014-10-08 14:22:10 +04:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
def build_property_field(self, field_name, model_class):
|
2014-12-19 18:35:52 +03:00
|
|
|
"""
|
|
|
|
Create a read only field for model methods and properties.
|
|
|
|
"""
|
2014-12-20 00:32:43 +03:00
|
|
|
field_class = ReadOnlyField
|
|
|
|
field_kwargs = {}
|
2014-09-18 15:17:21 +04:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
return field_class, field_kwargs
|
2014-11-19 16:55:10 +03:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
def build_url_field(self, field_name, model_class):
|
2014-12-19 18:35:52 +03:00
|
|
|
"""
|
|
|
|
Create a field representing the object's own URL.
|
|
|
|
"""
|
2015-02-06 18:45:02 +03:00
|
|
|
field_class = self.serializer_url_field
|
2014-12-20 00:32:43 +03:00
|
|
|
field_kwargs = get_url_kwargs(model_class)
|
2014-11-19 16:55:10 +03:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
return field_class, field_kwargs
|
2014-09-18 15:17:21 +04:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
def build_unknown_field(self, field_name, model_class):
|
2014-12-19 18:35:52 +03:00
|
|
|
"""
|
|
|
|
Raise an error on any unknown fields.
|
|
|
|
"""
|
|
|
|
raise ImproperlyConfigured(
|
|
|
|
'Field name `%s` is not valid for model `%s`.' %
|
2014-12-20 00:32:43 +03:00
|
|
|
(field_name, model_class.__name__)
|
2014-12-19 18:35:52 +03:00
|
|
|
)
|
2014-05-22 23:51:20 +04:00
|
|
|
|
2015-02-06 19:15:10 +03:00
|
|
|
def include_extra_kwargs(self, kwargs, extra_kwargs):
|
2014-12-19 18:09:57 +03:00
|
|
|
"""
|
2015-02-06 19:15:10 +03:00
|
|
|
Include any 'extra_kwargs' that have been included for this field,
|
2014-12-19 18:09:57 +03:00
|
|
|
possibly removing any incompatible existing keyword arguments.
|
|
|
|
"""
|
2015-02-06 19:15:10 +03:00
|
|
|
if extra_kwargs.get('read_only', False):
|
2014-12-19 18:09:57 +03:00
|
|
|
for attr in [
|
|
|
|
'required', 'default', 'allow_blank', 'allow_null',
|
|
|
|
'min_length', 'max_length', 'min_value', 'max_value',
|
|
|
|
'validators', 'queryset'
|
|
|
|
]:
|
|
|
|
kwargs.pop(attr, None)
|
2014-10-28 19:21:49 +03:00
|
|
|
|
2015-02-06 19:15:10 +03:00
|
|
|
if extra_kwargs.get('default') and kwargs.get('required') is False:
|
2014-12-19 18:09:57 +03:00
|
|
|
kwargs.pop('required')
|
|
|
|
|
2015-07-01 17:10:18 +03:00
|
|
|
if extra_kwargs.get('read_only', kwargs.get('read_only', False)):
|
|
|
|
extra_kwargs.pop('required', None) # Read only fields should always omit the 'required' argument.
|
2015-05-28 05:14:08 +03:00
|
|
|
|
2015-02-06 19:15:10 +03:00
|
|
|
kwargs.update(extra_kwargs)
|
2014-12-19 18:09:57 +03:00
|
|
|
|
|
|
|
return kwargs
|
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
# Methods for determining additional keyword arguments to apply...
|
|
|
|
|
|
|
|
def get_extra_kwargs(self):
|
2014-12-19 17:51:45 +03:00
|
|
|
"""
|
2014-12-19 18:35:52 +03:00
|
|
|
Return a dictionary mapping field names to a dictionary of
|
|
|
|
additional keyword arguments.
|
2014-12-19 17:51:45 +03:00
|
|
|
"""
|
2016-01-06 23:04:51 +03:00
|
|
|
extra_kwargs = copy.deepcopy(getattr(self.Meta, 'extra_kwargs', {}))
|
2012-09-20 16:06:27 +04:00
|
|
|
|
2014-10-08 19:09:37 +04:00
|
|
|
read_only_fields = getattr(self.Meta, 'read_only_fields', None)
|
|
|
|
if read_only_fields is not None:
|
2016-06-13 15:31:12 +03:00
|
|
|
if not isinstance(read_only_fields, (list, tuple)):
|
|
|
|
raise TypeError(
|
|
|
|
'The `read_only_fields` option must be a list or tuple. '
|
|
|
|
'Got %s.' % type(read_only_fields).__name__
|
|
|
|
)
|
2014-10-08 19:09:37 +04:00
|
|
|
for field_name in read_only_fields:
|
|
|
|
kwargs = extra_kwargs.get(field_name, {})
|
|
|
|
kwargs['read_only'] = True
|
|
|
|
extra_kwargs[field_name] = kwargs
|
|
|
|
|
2017-02-22 14:06:48 +03:00
|
|
|
else:
|
|
|
|
# Guard against the possible misspelling `readonly_fields` (used
|
|
|
|
# by the Django admin and others).
|
|
|
|
assert not hasattr(self.Meta, 'readonly_fields'), (
|
|
|
|
'Serializer `%s.%s` has field `readonly_fields`; '
|
|
|
|
'the correct spelling for the option is `read_only_fields`.' %
|
|
|
|
(self.__class__.__module__, self.__class__.__name__)
|
|
|
|
)
|
|
|
|
|
2014-10-08 19:09:37 +04:00
|
|
|
return extra_kwargs
|
|
|
|
|
2014-12-19 17:51:45 +03:00
|
|
|
def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs):
|
|
|
|
"""
|
|
|
|
Return any additional field options that need to be included as a
|
|
|
|
result of uniqueness constraints on the model. This is returned as
|
|
|
|
a two-tuple of:
|
|
|
|
|
|
|
|
('dict of updated extra kwargs', 'mapping of hidden fields')
|
|
|
|
"""
|
2016-06-13 15:31:12 +03:00
|
|
|
if getattr(self.Meta, 'validators', None) is not None:
|
|
|
|
return (extra_kwargs, {})
|
|
|
|
|
2014-12-19 16:13:20 +03:00
|
|
|
model = getattr(self.Meta, 'model')
|
2014-12-19 17:51:45 +03:00
|
|
|
model_fields = self._get_model_fields(
|
|
|
|
field_names, declared_fields, extra_kwargs
|
|
|
|
)
|
2014-12-19 16:13:20 +03:00
|
|
|
|
|
|
|
# Determine if we need any additional `HiddenField` or extra keyword
|
|
|
|
# arguments to deal with `unique_for` dates that are required to
|
|
|
|
# be in the input data in order to validate it.
|
|
|
|
unique_constraint_names = set()
|
|
|
|
|
|
|
|
for model_field in model_fields.values():
|
|
|
|
# Include each of the `unique_for_*` field names.
|
2015-10-17 12:00:11 +03:00
|
|
|
unique_constraint_names |= {model_field.unique_for_date, model_field.unique_for_month,
|
|
|
|
model_field.unique_for_year}
|
2014-12-19 16:13:20 +03:00
|
|
|
|
2015-10-17 12:00:11 +03:00
|
|
|
unique_constraint_names -= {None}
|
2014-12-19 16:13:20 +03:00
|
|
|
|
|
|
|
# Include each of the `unique_together` field names,
|
|
|
|
# so long as all the field names are included on the serializer.
|
2018-01-08 12:49:46 +03:00
|
|
|
for parent_class in [model] + list(model._meta.parents):
|
2014-12-19 16:13:20 +03:00
|
|
|
for unique_together_list in parent_class._meta.unique_together:
|
|
|
|
if set(field_names).issuperset(set(unique_together_list)):
|
|
|
|
unique_constraint_names |= set(unique_together_list)
|
|
|
|
|
|
|
|
# Now we have all the field names that have uniqueness constraints
|
|
|
|
# applied, we can add the extra 'required=...' or 'default=...'
|
|
|
|
# arguments that are appropriate to these fields, or add a `HiddenField` for it.
|
|
|
|
hidden_fields = {}
|
2014-12-19 17:51:45 +03:00
|
|
|
uniqueness_extra_kwargs = {}
|
2014-12-19 16:13:20 +03:00
|
|
|
|
|
|
|
for unique_constraint_name in unique_constraint_names:
|
|
|
|
# Get the model field that is referred too.
|
|
|
|
unique_constraint_field = model._meta.get_field(unique_constraint_name)
|
|
|
|
|
|
|
|
if getattr(unique_constraint_field, 'auto_now_add', None):
|
|
|
|
default = CreateOnlyDefault(timezone.now)
|
|
|
|
elif getattr(unique_constraint_field, 'auto_now', None):
|
|
|
|
default = timezone.now
|
|
|
|
elif unique_constraint_field.has_default():
|
|
|
|
default = unique_constraint_field.default
|
|
|
|
else:
|
|
|
|
default = empty
|
|
|
|
|
|
|
|
if unique_constraint_name in model_fields:
|
|
|
|
# The corresponding field is present in the serializer
|
|
|
|
if default is empty:
|
2014-12-19 17:51:45 +03:00
|
|
|
uniqueness_extra_kwargs[unique_constraint_name] = {'required': True}
|
2014-12-19 16:13:20 +03:00
|
|
|
else:
|
2014-12-19 17:51:45 +03:00
|
|
|
uniqueness_extra_kwargs[unique_constraint_name] = {'default': default}
|
2014-12-19 16:13:20 +03:00
|
|
|
elif default is not empty:
|
2016-06-13 15:31:12 +03:00
|
|
|
# The corresponding field is not present in the
|
2014-12-19 16:13:20 +03:00
|
|
|
# serializer. We have a default to use for it, so
|
|
|
|
# add in a hidden field that populates it.
|
|
|
|
hidden_fields[unique_constraint_name] = HiddenField(default=default)
|
|
|
|
|
2014-12-19 17:51:45 +03:00
|
|
|
# Update `extra_kwargs` with any new options.
|
|
|
|
for key, value in uniqueness_extra_kwargs.items():
|
|
|
|
if key in extra_kwargs:
|
2016-08-02 16:33:15 +03:00
|
|
|
value.update(extra_kwargs[key])
|
|
|
|
extra_kwargs[key] = value
|
2014-12-19 17:51:45 +03:00
|
|
|
|
2014-12-19 16:13:20 +03:00
|
|
|
return extra_kwargs, hidden_fields
|
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
def _get_model_fields(self, field_names, declared_fields, extra_kwargs):
|
2014-12-19 15:27:50 +03:00
|
|
|
"""
|
2014-12-19 18:35:52 +03:00
|
|
|
Returns all the model fields that are being mapped to by fields
|
|
|
|
on the serializer class.
|
|
|
|
Returned as a dict of 'model field name' -> 'model field'.
|
|
|
|
Used internally by `get_uniqueness_field_options`.
|
2014-12-19 15:27:50 +03:00
|
|
|
"""
|
2014-12-19 18:35:52 +03:00
|
|
|
model = getattr(self.Meta, 'model')
|
|
|
|
model_fields = {}
|
2014-12-19 15:27:50 +03:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
for field_name in field_names:
|
|
|
|
if field_name in declared_fields:
|
|
|
|
# If the field is declared on the serializer
|
|
|
|
field = declared_fields[field_name]
|
|
|
|
source = field.source or field_name
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
source = extra_kwargs[field_name]['source']
|
|
|
|
except KeyError:
|
|
|
|
source = field_name
|
2014-10-08 19:09:37 +04:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
if '.' in source or source == '*':
|
|
|
|
# Model fields will always have a simple source mapping,
|
|
|
|
# they can't be nested attribute lookups.
|
|
|
|
continue
|
2014-10-08 19:09:37 +04:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
try:
|
2015-01-23 17:56:15 +03:00
|
|
|
field = model._meta.get_field(source)
|
|
|
|
if isinstance(field, DjangoModelField):
|
|
|
|
model_fields[source] = field
|
2014-12-19 18:35:52 +03:00
|
|
|
except FieldDoesNotExist:
|
|
|
|
pass
|
2014-10-08 19:09:37 +04:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
return model_fields
|
2014-10-08 19:09:37 +04:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
# Determine the validators to apply...
|
2014-10-08 19:09:37 +04:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
def get_validators(self):
|
2014-12-19 15:18:40 +03:00
|
|
|
"""
|
2014-12-19 18:35:52 +03:00
|
|
|
Determine the set of validators to use when instantiating serializer.
|
2014-12-19 15:18:40 +03:00
|
|
|
"""
|
2014-12-19 18:35:52 +03:00
|
|
|
# If the validators have been declared explicitly then use that.
|
|
|
|
validators = getattr(getattr(self, 'Meta', None), 'validators', None)
|
|
|
|
if validators is not None:
|
2019-02-19 18:38:20 +03:00
|
|
|
return list(validators)
|
2014-12-19 15:18:40 +03:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
# Otherwise use the default set of validators.
|
2014-09-18 14:20:56 +04:00
|
|
|
return (
|
2014-12-19 18:35:52 +03:00
|
|
|
self.get_unique_together_validators() +
|
|
|
|
self.get_unique_for_date_validators()
|
2014-09-18 14:20:56 +04:00
|
|
|
)
|
2013-04-30 11:24:33 +04:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
def get_unique_together_validators(self):
|
|
|
|
"""
|
2016-08-08 11:32:22 +03:00
|
|
|
Determine a default set of validators for any unique_together constraints.
|
2014-12-19 18:35:52 +03:00
|
|
|
"""
|
|
|
|
model_class_inheritance_tree = (
|
|
|
|
[self.Meta.model] +
|
2018-01-08 12:49:46 +03:00
|
|
|
list(self.Meta.model._meta.parents)
|
2014-12-19 18:35:52 +03:00
|
|
|
)
|
2014-12-19 15:18:40 +03:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
# The field names we're passing though here only include fields
|
|
|
|
# which may map onto a model field. Any dotted field name lookups
|
|
|
|
# cannot map to a field, and must be a traversal, so we're not
|
|
|
|
# including those.
|
2015-10-17 12:00:11 +03:00
|
|
|
field_names = {
|
2016-07-27 17:40:04 +03:00
|
|
|
field.source for field in self._writable_fields
|
2014-12-19 18:35:52 +03:00
|
|
|
if (field.source != '*') and ('.' not in field.source)
|
2015-10-17 12:00:11 +03:00
|
|
|
}
|
2014-12-19 15:18:40 +03:00
|
|
|
|
2018-04-06 16:20:54 +03:00
|
|
|
# Special Case: Add read_only fields with defaults.
|
|
|
|
field_names |= {
|
|
|
|
field.source for field in self.fields.values()
|
|
|
|
if (field.read_only) and (field.default != empty) and (field.source != '*') and ('.' not in field.source)
|
|
|
|
}
|
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
# Note that we make sure to check `unique_together` both on the
|
|
|
|
# base model class, but also on any parent classes.
|
|
|
|
validators = []
|
|
|
|
for parent_class in model_class_inheritance_tree:
|
|
|
|
for unique_together in parent_class._meta.unique_together:
|
|
|
|
if field_names.issuperset(set(unique_together)):
|
|
|
|
validator = UniqueTogetherValidator(
|
|
|
|
queryset=parent_class._default_manager,
|
|
|
|
fields=unique_together
|
2014-12-19 15:18:40 +03:00
|
|
|
)
|
2014-12-19 18:35:52 +03:00
|
|
|
validators.append(validator)
|
|
|
|
return validators
|
2014-12-19 15:18:40 +03:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
def get_unique_for_date_validators(self):
|
2014-12-19 15:18:40 +03:00
|
|
|
"""
|
2016-08-08 11:32:22 +03:00
|
|
|
Determine a default set of validators for the following constraints:
|
2014-12-19 18:35:52 +03:00
|
|
|
|
|
|
|
* unique_for_date
|
|
|
|
* unique_for_month
|
|
|
|
* unique_for_year
|
2014-12-19 15:18:40 +03:00
|
|
|
"""
|
2014-12-19 18:35:52 +03:00
|
|
|
info = model_meta.get_field_info(self.Meta.model)
|
|
|
|
default_manager = self.Meta.model._default_manager
|
|
|
|
field_names = [field.source for field in self.fields.values()]
|
2013-04-30 11:24:33 +04:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
validators = []
|
2014-12-05 02:29:28 +03:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
for field_name, field in info.fields_and_pk.items():
|
|
|
|
if field.unique_for_date and field_name in field_names:
|
|
|
|
validator = UniqueForDateValidator(
|
|
|
|
queryset=default_manager,
|
|
|
|
field=field_name,
|
|
|
|
date_field=field.unique_for_date
|
|
|
|
)
|
|
|
|
validators.append(validator)
|
2014-12-05 02:29:28 +03:00
|
|
|
|
2014-12-19 18:35:52 +03:00
|
|
|
if field.unique_for_month and field_name in field_names:
|
|
|
|
validator = UniqueForMonthValidator(
|
|
|
|
queryset=default_manager,
|
|
|
|
field=field_name,
|
|
|
|
date_field=field.unique_for_month
|
|
|
|
)
|
|
|
|
validators.append(validator)
|
|
|
|
|
|
|
|
if field.unique_for_year and field_name in field_names:
|
|
|
|
validator = UniqueForYearValidator(
|
|
|
|
queryset=default_manager,
|
|
|
|
field=field_name,
|
|
|
|
date_field=field.unique_for_year
|
|
|
|
)
|
|
|
|
validators.append(validator)
|
|
|
|
|
|
|
|
return validators
|
2012-10-04 14:26:41 +04:00
|
|
|
|
|
|
|
|
2015-01-23 18:24:06 +03:00
|
|
|
if hasattr(models, 'UUIDField'):
|
2015-01-30 18:36:03 +03:00
|
|
|
ModelSerializer.serializer_field_mapping[models.UUIDField] = UUIDField
|
2015-01-23 18:24:06 +03:00
|
|
|
|
2015-02-28 10:18:47 +03:00
|
|
|
# IPAddressField is deprecated in Django
|
|
|
|
if hasattr(models, 'IPAddressField'):
|
2015-02-28 14:29:27 +03:00
|
|
|
ModelSerializer.serializer_field_mapping[models.IPAddressField] = IPAddressField
|
2015-02-28 10:18:47 +03:00
|
|
|
|
2015-01-23 19:27:23 +03:00
|
|
|
if postgres_fields:
|
2018-01-15 17:52:30 +03:00
|
|
|
ModelSerializer.serializer_field_mapping[postgres_fields.HStoreField] = HStoreField
|
2015-02-01 22:33:34 +03:00
|
|
|
ModelSerializer.serializer_field_mapping[postgres_fields.ArrayField] = ListField
|
2017-10-05 21:41:38 +03:00
|
|
|
ModelSerializer.serializer_field_mapping[postgres_fields.JSONField] = JSONField
|
2015-01-23 19:27:23 +03:00
|
|
|
|
2015-01-23 18:24:06 +03:00
|
|
|
|
2012-10-04 14:26:41 +04:00
|
|
|
class HyperlinkedModelSerializer(ModelSerializer):
|
2014-11-07 13:13:46 +03:00
|
|
|
"""
|
|
|
|
A type of `ModelSerializer` that uses hyperlinked relationships instead
|
|
|
|
of primary key relationships. Specifically:
|
|
|
|
|
|
|
|
* A 'url' field is included instead of the 'id' field.
|
|
|
|
* Relationships to other instances are hyperlinks, instead of primary keys.
|
|
|
|
"""
|
2015-02-06 18:45:02 +03:00
|
|
|
serializer_related_field = HyperlinkedRelatedField
|
2014-09-18 14:20:56 +04:00
|
|
|
|
2014-12-19 15:18:40 +03:00
|
|
|
def get_default_field_names(self, declared_fields, model_info):
|
|
|
|
"""
|
|
|
|
Return the default list of field names that will be used if the
|
|
|
|
`Meta.fields` option is not specified.
|
|
|
|
"""
|
2014-09-18 14:20:56 +04:00
|
|
|
return (
|
2015-07-14 13:21:33 +03:00
|
|
|
[self.url_field_name] +
|
2018-01-08 12:49:46 +03:00
|
|
|
list(declared_fields) +
|
|
|
|
list(model_info.fields) +
|
|
|
|
list(model_info.forward_relations)
|
2014-09-18 14:20:56 +04:00
|
|
|
)
|
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
def build_nested_field(self, field_name, relation_info, nested_depth):
|
2014-12-19 18:35:52 +03:00
|
|
|
"""
|
|
|
|
Create nested fields for forward and reverse relationships.
|
|
|
|
"""
|
2014-09-18 14:20:56 +04:00
|
|
|
class NestedSerializer(HyperlinkedModelSerializer):
|
|
|
|
class Meta:
|
2014-12-20 00:32:43 +03:00
|
|
|
model = relation_info.related_model
|
2014-12-19 17:52:53 +03:00
|
|
|
depth = nested_depth - 1
|
2016-06-02 16:39:10 +03:00
|
|
|
fields = '__all__'
|
2014-12-05 02:29:28 +03:00
|
|
|
|
2014-12-20 00:32:43 +03:00
|
|
|
field_class = NestedSerializer
|
|
|
|
field_kwargs = get_nested_relation_kwargs(relation_info)
|
|
|
|
|
|
|
|
return field_class, field_kwargs
|