| 1 |
""" |
| 2 |
Serializers and ModelSerializers are similar to Forms and ModelForms. |
| 3 |
Unlike forms, they are not constrained to dealing with HTML output, and |
| 4 |
form encoded input. |
| 5 |
|
| 6 |
Serialization in REST framework is a two-phase process: |
| 7 |
|
| 8 |
1. Serializers marshal between complex types like model instances, and |
| 9 |
python primitives. |
| 10 |
2. The process of marshaling between python primitives and request and |
| 11 |
response content is handled by parsers and renderers. |
| 12 |
""" |
| 13 |
|
| 14 |
import contextlib |
| 15 |
import copy |
| 16 |
import inspect |
| 17 |
import traceback |
| 18 |
import warnings |
| 19 |
from collections import defaultdict |
| 20 |
from collections.abc import Mapping |
| 21 |
|
| 22 |
from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured |
| 23 |
from django.core.exceptions import ValidationError as DjangoValidationError |
| 24 |
from django.db import models |
| 25 |
from django.db.models.fields import Field as DjangoModelField |
| 26 |
from django.utils import timezone |
| 27 |
from django.utils.functional import cached_property |
| 28 |
from django.utils.translation import gettext_lazy as _ |
| 29 |
|
| 30 |
from rest_framework.compat import postgres_fields |
| 31 |
from rest_framework.deprecation import RemovedInDRF320Warning |
| 32 |
from rest_framework.exceptions import ErrorDetail, ValidationError |
| 33 |
from rest_framework.fields import get_error_detail |
| 34 |
from rest_framework.settings import api_settings |
| 35 |
from rest_framework.utils import html, model_meta, representation |
| 36 |
from rest_framework.utils.field_mapping import ( |
| 37 |
ClassLookupDict, get_field_kwargs, get_nested_relation_kwargs, |
| 38 |
get_relation_kwargs, get_url_kwargs |
| 39 |
) |
| 40 |
from rest_framework.utils.serializer_helpers import ( |
| 41 |
BindingDict, BoundField, JSONBoundField, NestedBoundField, ReturnDict, |
| 42 |
ReturnList |
| 43 |
) |
| 44 |
from rest_framework.validators import ( |
| 45 |
UniqueForDateValidator, UniqueForMonthValidator, UniqueForYearValidator, |
| 46 |
UniqueTogetherValidator |
| 47 |
) |
| 48 |
|
| 49 |
# Note: We do the following so that users of the framework can use this style: |
| 50 |
# |
| 51 |
# example_field = serializers.CharField(...) |
| 52 |
# |
| 53 |
# This helps keep the separation between model fields, form fields, and |
| 54 |
# serializer fields more explicit. |
| 55 |
from rest_framework.fields import ( # NOQA # isort:skip |
| 56 |
BigIntegerField, BooleanField, CharField, ChoiceField, DateField, DateTimeField, DecimalField, |
| 57 |
DictField, DurationField, EmailField, Field, FileField, FilePathField, FloatField, |
| 58 |
HiddenField, HStoreField, IPAddressField, ImageField, IntegerField, JSONField, |
| 59 |
ListField, ModelField, MultipleChoiceField, ReadOnlyField, |
| 60 |
RegexField, SerializerMethodField, SlugField, TimeField, URLField, UUIDField, |
| 61 |
) |
| 62 |
from rest_framework.relations import ( # NOQA # isort:skip |
| 63 |
HyperlinkedIdentityField, HyperlinkedRelatedField, ManyRelatedField, |
| 64 |
PrimaryKeyRelatedField, RelatedField, SlugRelatedField, StringRelatedField, |
| 65 |
) |
| 66 |
|
| 67 |
# Non-field imports, but public API |
| 68 |
from rest_framework.fields import ( # NOQA # isort:skip |
| 69 |
CreateOnlyDefault, CurrentUserDefault, SkipField, empty |
| 70 |
) |
| 71 |
from rest_framework.relations import Hyperlink, PKOnlyObject # NOQA # isort:skip |
| 72 |
|
| 73 |
# We assume that 'validators' are intended for the child serializer, |
| 74 |
# rather than the parent serializer. |
| 75 |
LIST_SERIALIZER_KWARGS = ( |
| 76 |
'read_only', 'write_only', 'required', 'default', 'initial', 'source', |
| 77 |
'label', 'help_text', 'style', 'error_messages', 'allow_empty', |
| 78 |
'instance', 'data', 'partial', 'context', 'allow_null', |
| 79 |
'max_length', 'min_length' |
| 80 |
) |
| 81 |
LIST_SERIALIZER_KWARGS_REMOVE = ('allow_empty', 'min_length', 'max_length') |
| 82 |
|
| 83 |
ALL_FIELDS = '__all__' |
| 84 |
|
| 85 |
|
| 86 |
# BaseSerializer |
| 87 |
# -------------- |
| 88 |
|
| 89 |
class BaseSerializer(Field): |
| 90 |
""" |
| 91 |
The BaseSerializer class provides a minimal class which may be used |
| 92 |
for writing custom serializer implementations. |
| 93 |
|
| 94 |
Note that we strongly restrict the ordering of operations/properties |
| 95 |
that may be used on the serializer in order to enforce correct usage. |
| 96 |
|
| 97 |
In particular, if a `data=` argument is passed then: |
| 98 |
|
| 99 |
.is_valid() - Available. |
| 100 |
.initial_data - Available. |
| 101 |
.validated_data - Only available after calling `is_valid()` |
| 102 |
.errors - Only available after calling `is_valid()` |
| 103 |
.data - Only available after calling `is_valid()` |
| 104 |
|
| 105 |
If a `data=` argument is not passed then: |
| 106 |
|
| 107 |
.is_valid() - Not available. |
| 108 |
.initial_data - Not available. |
| 109 |
.validated_data - Not available. |
| 110 |
.errors - Not available. |
| 111 |
.data - Available. |
| 112 |
""" |
| 113 |
|
| 114 |
def __init__(self, instance=None, data=empty, **kwargs): |
| 115 |
self.instance = instance |
| 116 |
if data is not empty: |
| 117 |
self.initial_data = data |
| 118 |
self.partial = kwargs.pop('partial', False) |
| 119 |
self._context = kwargs.pop('context', {}) |
| 120 |
kwargs.pop('many', None) |
| 121 |
super().__init__(**kwargs) |
| 122 |
|
| 123 |
def __new__(cls, *args, **kwargs): |
| 124 |
# We override this method in order to automatically create |
| 125 |
# `ListSerializer` classes instead when `many=True` is set. |
| 126 |
if kwargs.pop('many', False): |
| 127 |
return cls.many_init(*args, **kwargs) |
| 128 |
return super().__new__(cls, *args, **kwargs) |
| 129 |
|
| 130 |
# Allow type checkers to make serializers generic. |
| 131 |
def __class_getitem__(cls, *args, **kwargs): |
| 132 |
return cls |
| 133 |
|
| 134 |
@classmethod |
| 135 |
def many_init(cls, *args, **kwargs): |
| 136 |
""" |
| 137 |
This method implements the creation of a `ListSerializer` parent |
| 138 |
class when `many=True` is used. You can customize it if you need to |
| 139 |
control which keyword arguments are passed to the parent, and |
| 140 |
which are passed to the child. |
| 141 |
|
| 142 |
Note that we're over-cautious in passing most arguments to both parent |
| 143 |
and child classes in order to try to cover the general case. If you're |
| 144 |
overriding this method you'll probably want something much simpler, eg: |
| 145 |
|
| 146 |
@classmethod |
| 147 |
def many_init(cls, *args, **kwargs): |
| 148 |
kwargs['child'] = cls() |
| 149 |
return CustomListSerializer(*args, **kwargs) |
| 150 |
""" |
| 151 |
list_kwargs = {} |
| 152 |
for key in LIST_SERIALIZER_KWARGS_REMOVE: |
| 153 |
value = kwargs.pop(key, None) |
| 154 |
if value is not None: |
| 155 |
list_kwargs[key] = value |
| 156 |
list_kwargs['child'] = cls(*args, **kwargs) |
| 157 |
list_kwargs.update({ |
| 158 |
key: value for key, value in kwargs.items() |
| 159 |
if key in LIST_SERIALIZER_KWARGS |
| 160 |
}) |
| 161 |
meta = getattr(cls, 'Meta', None) |
| 162 |
list_serializer_class = getattr(meta, 'list_serializer_class', ListSerializer) |
| 163 |
return list_serializer_class(*args, **list_kwargs) |
| 164 |
|
| 165 |
def to_internal_value(self, data): |
| 166 |
raise NotImplementedError('`to_internal_value()` must be implemented.') |
| 167 |
|
| 168 |
def to_representation(self, instance): |
| 169 |
raise NotImplementedError('`to_representation()` must be implemented.') |
| 170 |
|
| 171 |
def update(self, instance, validated_data): |
| 172 |
raise NotImplementedError('`update()` must be implemented.') |
| 173 |
|
| 174 |
def create(self, validated_data): |
| 175 |
raise NotImplementedError('`create()` must be implemented.') |
| 176 |
|
| 177 |
def save(self, **kwargs): |
| 178 |
assert hasattr(self, '_errors'), ( |
| 179 |
'You must call `.is_valid()` before calling `.save()`.' |
| 180 |
) |
| 181 |
|
| 182 |
assert not self.errors, ( |
| 183 |
'You cannot call `.save()` on a serializer with invalid data.' |
| 184 |
) |
| 185 |
|
| 186 |
# Guard against incorrect use of `serializer.save(commit=False)` |
| 187 |
assert 'commit' not in kwargs, ( |
| 188 |
"'commit' is not a valid keyword argument to the 'save()' method. " |
| 189 |
"If you need to access data before committing to the database then " |
| 190 |
"inspect 'serializer.validated_data' instead. " |
| 191 |
"You can also pass additional keyword arguments to 'save()' if you " |
| 192 |
"need to set extra attributes on the saved model instance. " |
| 193 |
"For example: 'serializer.save(owner=request.user)'.'" |
| 194 |
) |
| 195 |
|
| 196 |
assert not hasattr(self, '_data'), ( |
| 197 |
"You cannot call `.save()` after accessing `serializer.data`." |
| 198 |
"If you need to access data before committing to the database then " |
| 199 |
"inspect 'serializer.validated_data' instead. " |
| 200 |
) |
| 201 |
|
| 202 |
validated_data = {**self.validated_data, **kwargs} |
| 203 |
|
| 204 |
if self.instance is not None: |
| 205 |
self.instance = self.update(self.instance, validated_data) |
| 206 |
assert self.instance is not None, ( |
| 207 |
'`update()` did not return an object instance.' |
| 208 |
) |
| 209 |
else: |
| 210 |
self.instance = self.create(validated_data) |
| 211 |
assert self.instance is not None, ( |
| 212 |
'`create()` did not return an object instance.' |
| 213 |
) |
| 214 |
|
| 215 |
return self.instance |
| 216 |
|
| 217 |
def is_valid(self, *, raise_exception=False): |
| 218 |
assert hasattr(self, 'initial_data'), ( |
| 219 |
'Cannot call `.is_valid()` as no `data=` keyword argument was ' |
| 220 |
'passed when instantiating the serializer instance.' |
| 221 |
) |
| 222 |
|
| 223 |
if not hasattr(self, '_validated_data'): |
| 224 |
try: |
| 225 |
self._validated_data = self.run_validation(self.initial_data) |
| 226 |
except ValidationError as exc: |
| 227 |
self._validated_data = {} |
| 228 |
self._errors = exc.detail |
| 229 |
else: |
| 230 |
self._errors = {} |
| 231 |
|
| 232 |
if self._errors and raise_exception: |
| 233 |
raise ValidationError(self.errors) |
| 234 |
|
| 235 |
return not bool(self._errors) |
| 236 |
|
| 237 |
@property |
| 238 |
def data(self): |
| 239 |
if hasattr(self, 'initial_data') and not hasattr(self, '_validated_data'): |
| 240 |
msg = ( |
| 241 |
'When a serializer is passed a `data` keyword argument you ' |
| 242 |
'must call `.is_valid()` before attempting to access the ' |
| 243 |
'serialized `.data` representation.\n' |
| 244 |
'You should either call `.is_valid()` first, ' |
| 245 |
'or access `.initial_data` instead.' |
| 246 |
) |
| 247 |
raise AssertionError(msg) |
| 248 |
|
| 249 |
if not hasattr(self, '_data'): |
| 250 |
if self.instance is not None and not getattr(self, '_errors', None): |
| 251 |
self._data = self.to_representation(self.instance) |
| 252 |
elif hasattr(self, '_validated_data') and not getattr(self, '_errors', None): |
| 253 |
self._data = self.to_representation(self.validated_data) |
| 254 |
else: |
| 255 |
self._data = self.get_initial() |
| 256 |
return self._data |
| 257 |
|
| 258 |
@property |
| 259 |
def errors(self): |
| 260 |
if not hasattr(self, '_errors'): |
| 261 |
msg = 'You must call `.is_valid()` before accessing `.errors`.' |
| 262 |
raise AssertionError(msg) |
| 263 |
return self._errors |
| 264 |
|
| 265 |
@property |
| 266 |
def validated_data(self): |
| 267 |
if not hasattr(self, '_validated_data'): |
| 268 |
msg = 'You must call `.is_valid()` before accessing `.validated_data`.' |
| 269 |
raise AssertionError(msg) |
| 270 |
return self._validated_data |
| 271 |
|
| 272 |
|
| 273 |
# Serializer & ListSerializer classes |
| 274 |
# ----------------------------------- |
| 275 |
|
| 276 |
class SerializerMetaclass(type): |
| 277 |
""" |
| 278 |
This metaclass sets a dictionary named `_declared_fields` on the class. |
| 279 |
|
| 280 |
Any instances of `Field` included as attributes on either the class |
| 281 |
or on any of its superclasses will be include in the |
| 282 |
`_declared_fields` dictionary. |
| 283 |
""" |
| 284 |
|
| 285 |
@classmethod |
| 286 |
def _get_declared_fields(cls, bases, attrs): |
| 287 |
fields = [(field_name, attrs.pop(field_name)) |
| 288 |
for field_name, obj in list(attrs.items()) |
| 289 |
if isinstance(obj, Field)] |
| 290 |
fields.sort(key=lambda x: x[1]._creation_counter) |
| 291 |
|
| 292 |
# Ensures a base class field doesn't override cls attrs, and maintains |
| 293 |
# field precedence when inheriting multiple parents. e.g. if there is a |
| 294 |
# class C(A, B), and A and B both define 'field', use 'field' from A. |
| 295 |
known = set(attrs) |
| 296 |
|
| 297 |
def visit(name): |
| 298 |
known.add(name) |
| 299 |
return name |
| 300 |
|
| 301 |
base_fields = [ |
| 302 |
(visit(name), f) |
| 303 |
for base in bases if hasattr(base, '_declared_fields') |
| 304 |
for name, f in base._declared_fields.items() if name not in known |
| 305 |
] |
| 306 |
|
| 307 |
return dict(base_fields + fields) |
| 308 |
|
| 309 |
def __new__(cls, name, bases, attrs): |
| 310 |
attrs['_declared_fields'] = cls._get_declared_fields(bases, attrs) |
| 311 |
return super().__new__(cls, name, bases, attrs) |
| 312 |
|
| 313 |
|
| 314 |
def as_serializer_error(exc): |
| 315 |
""" |
| 316 |
Coerce validation exceptions into a standardized serialized error format. |
| 317 |
|
| 318 |
This function normalizes both Django's `ValidationError` and REST |
| 319 |
framework's `ValidationError` into a dictionary structure compatible |
| 320 |
with serializer `.errors`, ensuring all values are represented as |
| 321 |
lists of error details. |
| 322 |
|
| 323 |
The returned structure conforms to the serializer error contract: |
| 324 |
- Field-specific errors are returned as '{field-name: [errors]}' |
| 325 |
- Non-field errors are returned under the 'NON_FIELD_ERRORS_KEY' |
| 326 |
""" |
| 327 |
assert isinstance(exc, (ValidationError, DjangoValidationError)) |
| 328 |
|
| 329 |
if isinstance(exc, DjangoValidationError): |
| 330 |
detail = get_error_detail(exc) |
| 331 |
else: |
| 332 |
detail = exc.detail |
| 333 |
|
| 334 |
if isinstance(detail, Mapping): |
| 335 |
# If errors may be a dict we use the standard {key: list of values}. |
| 336 |
# Here we ensure that all the values are *lists* of errors. |
| 337 |
return { |
| 338 |
key: value if isinstance(value, (list, Mapping)) else [value] |
| 339 |
for key, value in detail.items() |
| 340 |
} |
| 341 |
elif isinstance(detail, list): |
| 342 |
# Errors raised as a list are non-field errors. |
| 343 |
return { |
| 344 |
api_settings.NON_FIELD_ERRORS_KEY: detail |
| 345 |
} |
| 346 |
# Errors raised as a string are non-field errors. |
| 347 |
return { |
| 348 |
api_settings.NON_FIELD_ERRORS_KEY: [detail] |
| 349 |
} |
| 350 |
|
| 351 |
|
| 352 |
class Serializer(BaseSerializer, metaclass=SerializerMetaclass): |
| 353 |
default_error_messages = { |
| 354 |
'invalid': _('Invalid data. Expected a dictionary, but got {datatype}.') |
| 355 |
} |
| 356 |
|
| 357 |
def set_value(self, dictionary, keys, value): |
| 358 |
""" |
| 359 |
Similar to Python's built in `dictionary[key] = value`, |
| 360 |
but takes a list of nested keys instead of a single key. |
| 361 |
|
| 362 |
set_value({'a': 1}, [], {'b': 2}) -> {'a': 1, 'b': 2} |
| 363 |
set_value({'a': 1}, ['x'], 2) -> {'a': 1, 'x': 2} |
| 364 |
set_value({'a': 1}, ['x', 'y'], 2) -> {'a': 1, 'x': {'y': 2}} |
| 365 |
""" |
| 366 |
if not keys: |
| 367 |
dictionary.update(value) |
| 368 |
return |
| 369 |
|
| 370 |
for key in keys[:-1]: |
| 371 |
if key not in dictionary: |
| 372 |
dictionary[key] = {} |
| 373 |
dictionary = dictionary[key] |
| 374 |
|
| 375 |
dictionary[keys[-1]] = value |
| 376 |
|
| 377 |
@cached_property |
| 378 |
def fields(self): |
| 379 |
""" |
| 380 |
A dictionary of {field_name: field_instance}. |
| 381 |
""" |
| 382 |
# `fields` is evaluated lazily. We do this to ensure that we don't |
| 383 |
# have issues importing modules that use ModelSerializers as fields, |
| 384 |
# even if Django's app-loading stage has not yet run. |
| 385 |
fields = BindingDict(self) |
| 386 |
for key, value in self.get_fields().items(): |
| 387 |
fields[key] = value |
| 388 |
return fields |
| 389 |
|
| 390 |
@property |
| 391 |
def _writable_fields(self): |
| 392 |
for field in self.fields.values(): |
| 393 |
if not field.read_only: |
| 394 |
yield field |
| 395 |
|
| 396 |
@property |
| 397 |
def _readable_fields(self): |
| 398 |
for field in self.fields.values(): |
| 399 |
if not field.write_only: |
| 400 |
yield field |
| 401 |
|
| 402 |
def get_fields(self): |
| 403 |
""" |
| 404 |
Returns a dictionary of {field_name: field_instance}. |
| 405 |
""" |
| 406 |
# Every new serializer is created with a clone of the field instances. |
| 407 |
# This allows users to dynamically modify the fields on a serializer |
| 408 |
# instance without affecting every other serializer instance. |
| 409 |
return copy.deepcopy(self._declared_fields) |
| 410 |
|
| 411 |
def get_validators(self): |
| 412 |
""" |
| 413 |
Returns a list of validator callables. |
| 414 |
""" |
| 415 |
# Used by the lazily-evaluated `validators` property. |
| 416 |
meta = getattr(self, 'Meta', None) |
| 417 |
validators = getattr(meta, 'validators', None) |
| 418 |
return list(validators) if validators else [] |
| 419 |
|
| 420 |
def get_initial(self): |
| 421 |
if hasattr(self, 'initial_data'): |
| 422 |
# initial_data may not be a valid type |
| 423 |
if not isinstance(self.initial_data, Mapping): |
| 424 |
return {} |
| 425 |
|
| 426 |
return { |
| 427 |
field_name: field.get_value(self.initial_data) |
| 428 |
for field_name, field in self.fields.items() |
| 429 |
if (field.get_value(self.initial_data) is not empty) and |
| 430 |
not field.read_only |
| 431 |
} |
| 432 |
|
| 433 |
return { |
| 434 |
field.field_name: field.get_initial() |
| 435 |
for field in self.fields.values() |
| 436 |
if not field.read_only |
| 437 |
} |
| 438 |
|
| 439 |
def get_value(self, dictionary): |
| 440 |
# We override the default field access in order to support |
| 441 |
# nested HTML forms. |
| 442 |
if html.is_html_input(dictionary): |
| 443 |
return html.parse_html_dict(dictionary, prefix=self.field_name, default=empty) |
| 444 |
return dictionary.get(self.field_name, empty) |
| 445 |
|
| 446 |
def run_validation(self, data=empty): |
| 447 |
""" |
| 448 |
We override the default `run_validation`, because the validation |
| 449 |
performed by validators and the `.validate()` method should |
| 450 |
be coerced into an error dictionary with a 'non_fields_error' key. |
| 451 |
""" |
| 452 |
(is_empty_value, data) = self.validate_empty_values(data) |
| 453 |
if is_empty_value: |
| 454 |
return data |
| 455 |
|
| 456 |
value = self.to_internal_value(data) |
| 457 |
try: |
| 458 |
self.run_validators(value) |
| 459 |
value = self.validate(value) |
| 460 |
assert value is not None, '.validate() should return the validated data' |
| 461 |
except (ValidationError, DjangoValidationError) as exc: |
| 462 |
raise ValidationError(detail=as_serializer_error(exc)) |
| 463 |
|
| 464 |
return value |
| 465 |
|
| 466 |
def _read_only_defaults(self): |
| 467 |
fields = [ |
| 468 |
field for field in self.fields.values() |
| 469 |
if (field.read_only) and (field.default != empty) and (field.source != '*') and ('.' not in field.source) |
| 470 |
] |
| 471 |
|
| 472 |
defaults = {} |
| 473 |
for field in fields: |
| 474 |
try: |
| 475 |
default = field.get_default() |
| 476 |
except SkipField: |
| 477 |
continue |
| 478 |
defaults[field.source] = default |
| 479 |
|
| 480 |
return defaults |
| 481 |
|
| 482 |
def run_validators(self, value): |
| 483 |
""" |
| 484 |
Add read_only fields with defaults to value before running validators. |
| 485 |
""" |
| 486 |
if isinstance(value, dict): |
| 487 |
to_validate = self._read_only_defaults() |
| 488 |
to_validate.update(value) |
| 489 |
else: |
| 490 |
to_validate = value |
| 491 |
super().run_validators(to_validate) |
| 492 |
|
| 493 |
def to_internal_value(self, data): |
| 494 |
""" |
| 495 |
Dict of native values <- Dict of primitive datatypes. |
| 496 |
""" |
| 497 |
if not isinstance(data, Mapping): |
| 498 |
message = self.error_messages['invalid'].format( |
| 499 |
datatype=type(data).__name__ |
| 500 |
) |
| 501 |
raise ValidationError({ |
| 502 |
api_settings.NON_FIELD_ERRORS_KEY: [message] |
| 503 |
}, code='invalid') |
| 504 |
|
| 505 |
ret = {} |
| 506 |
errors = {} |
| 507 |
fields = self._writable_fields |
| 508 |
|
| 509 |
for field in fields: |
| 510 |
validate_method = getattr(self, 'validate_' + field.field_name, None) |
| 511 |
primitive_value = field.get_value(data) |
| 512 |
try: |
| 513 |
validated_value = field.run_validation(primitive_value) |
| 514 |
if validate_method is not None: |
| 515 |
validated_value = validate_method(validated_value) |
| 516 |
except ValidationError as exc: |
| 517 |
errors[field.field_name] = exc.detail |
| 518 |
except DjangoValidationError as exc: |
| 519 |
errors[field.field_name] = get_error_detail(exc) |
| 520 |
except SkipField: |
| 521 |
pass |
| 522 |
else: |
| 523 |
self.set_value(ret, field.source_attrs, validated_value) |
| 524 |
|
| 525 |
if errors: |
| 526 |
raise ValidationError(errors) |
| 527 |
|
| 528 |
return ret |
| 529 |
|
| 530 |
def to_representation(self, instance): |
| 531 |
""" |
| 532 |
Object instance -> Dict of primitive datatypes. |
| 533 |
""" |
| 534 |
ret = {} |
| 535 |
fields = self._readable_fields |
| 536 |
|
| 537 |
for field in fields: |
| 538 |
try: |
| 539 |
attribute = field.get_attribute(instance) |
| 540 |
except SkipField: |
| 541 |
continue |
| 542 |
|
| 543 |
# We skip `to_representation` for `None` values so that fields do |
| 544 |
# not have to explicitly deal with that case. |
| 545 |
# |
| 546 |
# For related fields with `use_pk_only_optimization` we need to |
| 547 |
# resolve the pk value. |
| 548 |
check_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else attribute |
| 549 |
if check_for_none is None: |
| 550 |
ret[field.field_name] = None |
| 551 |
else: |
| 552 |
ret[field.field_name] = field.to_representation(attribute) |
| 553 |
|
| 554 |
return ret |
| 555 |
|
| 556 |
def validate(self, attrs): |
| 557 |
return attrs |
| 558 |
|
| 559 |
def __repr__(self): |
| 560 |
return representation.serializer_repr(self, indent=1) |
| 561 |
|
| 562 |
# The following are used for accessing `BoundField` instances on the |
| 563 |
# serializer, for the purposes of presenting a form-like API onto the |
| 564 |
# field values and field errors. |
| 565 |
|
| 566 |
def __iter__(self): |
| 567 |
for field in self.fields.values(): |
| 568 |
yield self[field.field_name] |
| 569 |
|
| 570 |
def __getitem__(self, key): |
| 571 |
field = self.fields[key] |
| 572 |
value = self.data.get(key) |
| 573 |
error = self.errors.get(key) if hasattr(self, '_errors') else None |
| 574 |
if isinstance(field, Serializer): |
| 575 |
return NestedBoundField(field, value, error) |
| 576 |
if isinstance(field, JSONField): |
| 577 |
return JSONBoundField(field, value, error) |
| 578 |
return BoundField(field, value, error) |
| 579 |
|
| 580 |
# Include a backlink to the serializer class on return objects. |
| 581 |
# Allows renderers such as HTMLFormRenderer to get the full field info. |
| 582 |
|
| 583 |
@property |
| 584 |
def data(self): |
| 585 |
ret = super().data |
| 586 |
return ReturnDict(ret, serializer=self) |
| 587 |
|
| 588 |
@property |
| 589 |
def errors(self): |
| 590 |
ret = super().errors |
| 591 |
if isinstance(ret, list) and len(ret) == 1 and getattr(ret[0], 'code', None) == 'null': |
| 592 |
# Edge case. Provide a more descriptive error than |
| 593 |
# "this field may not be null", when no data is passed. |
| 594 |
detail = ErrorDetail('No data provided', code='null') |
| 595 |
ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]} |
| 596 |
return ReturnDict(ret, serializer=self) |
| 597 |
|
| 598 |
|
| 599 |
# There's some replication of `ListField` here, |
| 600 |
# but that's probably better than obfuscating the call hierarchy. |
| 601 |
|
| 602 |
class ListSerializer(BaseSerializer): |
| 603 |
child = None |
| 604 |
many = True |
| 605 |
|
| 606 |
default_error_messages = { |
| 607 |
'not_a_list': _('Expected a list of items but got type "{input_type}".'), |
| 608 |
'empty': _('This list may not be empty.'), |
| 609 |
'max_length': _('Ensure this field has no more than {max_length} elements.'), |
| 610 |
'min_length': _('Ensure this field has at least {min_length} elements.') |
| 611 |
} |
| 612 |
|
| 613 |
def __init__(self, *args, **kwargs): |
| 614 |
self.child = kwargs.pop('child', copy.deepcopy(self.child)) |
| 615 |
self.allow_empty = kwargs.pop('allow_empty', True) |
| 616 |
self.max_length = kwargs.pop('max_length', None) |
| 617 |
self.min_length = kwargs.pop('min_length', None) |
| 618 |
assert self.child is not None, '`child` is a required argument.' |
| 619 |
assert not inspect.isclass(self.child), '`child` has not been instantiated.' |
| 620 |
super().__init__(*args, **kwargs) |
| 621 |
self.child.bind(field_name='', parent=self) |
| 622 |
|
| 623 |
def get_initial(self): |
| 624 |
if hasattr(self, 'initial_data'): |
| 625 |
return self.to_representation(self.initial_data) |
| 626 |
return [] |
| 627 |
|
| 628 |
def get_value(self, dictionary): |
| 629 |
""" |
| 630 |
Given the input dictionary, return the field value. |
| 631 |
""" |
| 632 |
# We override the default field access in order to support |
| 633 |
# lists in HTML forms. |
| 634 |
if html.is_html_input(dictionary): |
| 635 |
return html.parse_html_list(dictionary, prefix=self.field_name, default=empty) |
| 636 |
return dictionary.get(self.field_name, empty) |
| 637 |
|
| 638 |
def run_validation(self, data=empty): |
| 639 |
""" |
| 640 |
We override the default `run_validation`, because the validation |
| 641 |
performed by validators and the `.validate()` method should |
| 642 |
be coerced into an error dictionary with a 'non_fields_error' key. |
| 643 |
""" |
| 644 |
(is_empty_value, data) = self.validate_empty_values(data) |
| 645 |
if is_empty_value: |
| 646 |
return data |
| 647 |
|
| 648 |
value = self.to_internal_value(data) |
| 649 |
try: |
| 650 |
self.run_validators(value) |
| 651 |
value = self.validate(value) |
| 652 |
assert value is not None, '.validate() should return the validated data' |
| 653 |
except (ValidationError, DjangoValidationError) as exc: |
| 654 |
raise ValidationError(detail=as_serializer_error(exc)) |
| 655 |
|
| 656 |
return value |
| 657 |
|
| 658 |
def run_child_validation(self, data): |
| 659 |
""" |
| 660 |
Run validation on child serializer. |
| 661 |
You may need to override this method to support multiple updates. For example: |
| 662 |
|
| 663 |
self.child.instance = self.instance.get(pk=data['id']) |
| 664 |
self.child.initial_data = data |
| 665 |
return super().run_child_validation(data) |
| 666 |
""" |
| 667 |
return self.child.run_validation(data) |
| 668 |
|
| 669 |
def to_internal_value(self, data): |
| 670 |
""" |
| 671 |
List of dicts of native values <- List of dicts of primitive datatypes. |
| 672 |
""" |
| 673 |
if html.is_html_input(data): |
| 674 |
data = html.parse_html_list(data, default=[]) |
| 675 |
|
| 676 |
if not isinstance(data, list): |
| 677 |
message = self.error_messages['not_a_list'].format( |
| 678 |
input_type=type(data).__name__ |
| 679 |
) |
| 680 |
raise ValidationError({ |
| 681 |
api_settings.NON_FIELD_ERRORS_KEY: [message] |
| 682 |
}, code='not_a_list') |
| 683 |
|
| 684 |
if not self.allow_empty and len(data) == 0: |
| 685 |
message = self.error_messages['empty'] |
| 686 |
raise ValidationError({ |
| 687 |
api_settings.NON_FIELD_ERRORS_KEY: [message] |
| 688 |
}, code='empty') |
| 689 |
|
| 690 |
if self.max_length is not None and len(data) > self.max_length: |
| 691 |
message = self.error_messages['max_length'].format(max_length=self.max_length) |
| 692 |
raise ValidationError({ |
| 693 |
api_settings.NON_FIELD_ERRORS_KEY: [message] |
| 694 |
}, code='max_length') |
| 695 |
|
| 696 |
if self.min_length is not None and len(data) < self.min_length: |
| 697 |
message = self.error_messages['min_length'].format(min_length=self.min_length) |
| 698 |
raise ValidationError({ |
| 699 |
api_settings.NON_FIELD_ERRORS_KEY: [message] |
| 700 |
}, code='min_length') |
| 701 |
|
| 702 |
ret = [] |
| 703 |
errors = {} |
| 704 |
|
| 705 |
for index, item in enumerate(data): |
| 706 |
try: |
| 707 |
validated = self.run_child_validation(item) |
| 708 |
except ValidationError as exc: |
| 709 |
errors[index] = exc.detail |
| 710 |
else: |
| 711 |
ret.append(validated) |
| 712 |
|
| 713 |
if errors: |
| 714 |
if not api_settings.LIST_SERIALIZER_ERRORS_AS_DICT: |
| 715 |
warnings.warn( |
| 716 |
'The list-based error format for `ListSerializer` is ' |
| 717 |
'deprecated and will be removed in DRF 3.20. Set ' |
| 718 |
'`REST_FRAMEWORK["LIST_SERIALIZER_ERRORS_AS_DICT"]` to ' |
| 719 |
'`True` to use the dictionary-based error format.', |
| 720 |
RemovedInDRF320Warning, |
| 721 |
stacklevel=4, |
| 722 |
) |
| 723 |
errors = [errors.get(index, {}) for index in range(len(data))] |
| 724 |
raise ValidationError(errors) |
| 725 |
|
| 726 |
return ret |
| 727 |
|
| 728 |
def to_representation(self, data): |
| 729 |
""" |
| 730 |
List of object instances -> List of dicts of primitive datatypes. |
| 731 |
""" |
| 732 |
# Dealing with nested relationships, data can be a Manager, |
| 733 |
# so, first get a queryset from the Manager if needed |
| 734 |
iterable = data.all() if isinstance(data, models.manager.BaseManager) else data |
| 735 |
|
| 736 |
return [ |
| 737 |
self.child.to_representation(item) for item in iterable |
| 738 |
] |
| 739 |
|
| 740 |
def validate(self, attrs): |
| 741 |
return attrs |
| 742 |
|
| 743 |
def update(self, instance, validated_data): |
| 744 |
raise NotImplementedError( |
| 745 |
"Serializers with many=True do not support multiple update by " |
| 746 |
"default, only multiple create. For updates it is unclear how to " |
| 747 |
"deal with insertions and deletions. If you need to support " |
| 748 |
"multiple update, use a `ListSerializer` class and override " |
| 749 |
"`.update()` so you can specify the behavior exactly." |
| 750 |
) |
| 751 |
|
| 752 |
def create(self, validated_data): |
| 753 |
return [ |
| 754 |
self.child.create(attrs) for attrs in validated_data |
| 755 |
] |
| 756 |
|
| 757 |
def save(self, **kwargs): |
| 758 |
""" |
| 759 |
Save and return a list of object instances. |
| 760 |
""" |
| 761 |
# Guard against incorrect use of `serializer.save(commit=False)` |
| 762 |
assert 'commit' not in kwargs, ( |
| 763 |
"'commit' is not a valid keyword argument to the 'save()' method. " |
| 764 |
"If you need to access data before committing to the database then " |
| 765 |
"inspect 'serializer.validated_data' instead. " |
| 766 |
"You can also pass additional keyword arguments to 'save()' if you " |
| 767 |
"need to set extra attributes on the saved model instance. " |
| 768 |
"For example: 'serializer.save(owner=request.user)'.'" |
| 769 |
) |
| 770 |
|
| 771 |
validated_data = [ |
| 772 |
{**attrs, **kwargs} for attrs in self.validated_data |
| 773 |
] |
| 774 |
|
| 775 |
if self.instance is not None: |
| 776 |
self.instance = self.update(self.instance, validated_data) |
| 777 |
assert self.instance is not None, ( |
| 778 |
'`update()` did not return an object instance.' |
| 779 |
) |
| 780 |
else: |
| 781 |
self.instance = self.create(validated_data) |
| 782 |
assert self.instance is not None, ( |
| 783 |
'`create()` did not return an object instance.' |
| 784 |
) |
| 785 |
|
| 786 |
return self.instance |
| 787 |
|
| 788 |
def is_valid(self, *, raise_exception=False): |
| 789 |
# This implementation is the same as the default, |
| 790 |
# except that we use lists, rather than dicts, as the empty case. |
| 791 |
assert hasattr(self, 'initial_data'), ( |
| 792 |
'Cannot call `.is_valid()` as no `data=` keyword argument was ' |
| 793 |
'passed when instantiating the serializer instance.' |
| 794 |
) |
| 795 |
|
| 796 |
if not hasattr(self, '_validated_data'): |
| 797 |
try: |
| 798 |
self._validated_data = self.run_validation(self.initial_data) |
| 799 |
except ValidationError as exc: |
| 800 |
self._validated_data = [] |
| 801 |
self._errors = exc.detail |
| 802 |
else: |
| 803 |
self._errors = [] |
| 804 |
|
| 805 |
if self._errors and raise_exception: |
| 806 |
raise ValidationError(self.errors) |
| 807 |
|
| 808 |
return not bool(self._errors) |
| 809 |
|
| 810 |
def __repr__(self): |
| 811 |
return representation.list_repr(self, indent=1) |
| 812 |
|
| 813 |
# Include a backlink to the serializer class on return objects. |
| 814 |
# Allows renderers such as HTMLFormRenderer to get the full field info. |
| 815 |
|
| 816 |
@property |
| 817 |
def data(self): |
| 818 |
ret = super().data |
| 819 |
return ReturnList(ret, serializer=self) |
| 820 |
|
| 821 |
@property |
| 822 |
def errors(self): |
| 823 |
ret = super().errors |
| 824 |
if isinstance(ret, list) and len(ret) == 1 and getattr(ret[0], 'code', None) == 'null': |
| 825 |
# Edge case. Provide a more descriptive error than |
| 826 |
# "this field may not be null", when no data is passed. |
| 827 |
detail = ErrorDetail('No data provided', code='null') |
| 828 |
ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]} |
| 829 |
if isinstance(ret, dict): |
| 830 |
return ReturnDict(ret, serializer=self) |
| 831 |
return ReturnList(ret, serializer=self) |
| 832 |
|
| 833 |
|
| 834 |
# ModelSerializer & HyperlinkedModelSerializer |
| 835 |
# -------------------------------------------- |
| 836 |
|
| 837 |
def raise_errors_on_nested_writes(method_name, serializer, validated_data): |
| 838 |
""" |
| 839 |
Enforce explicit handling of writable nested and dotted-source fields. |
| 840 |
|
| 841 |
This helper raises clear and actionable errors when a serializer attempts |
| 842 |
to perform writable nested updates or creates using the default |
| 843 |
`ModelSerializer` behavior. |
| 844 |
|
| 845 |
Writable nested relationships and dotted-source fields are intentionally |
| 846 |
unsupported by default due to ambiguous persistence semantics. Developers |
| 847 |
must either: |
| 848 |
- Override the `.create()` / `.update()` methods explicitly, or |
| 849 |
- Mark nested serializers as `read_only=True` |
| 850 |
|
| 851 |
This check is invoked internally by default `ModelSerializer.create()` |
| 852 |
and `ModelSerializer.update()` implementations. |
| 853 |
|
| 854 |
Eg. Suppose we have a `UserSerializer` with a nested profile. How should |
| 855 |
we handle the case of an update, where the `profile` relationship does |
| 856 |
not exist? Any of the following might be valid: |
| 857 |
* Raise an application error. |
| 858 |
* Silently ignore the nested part of the update. |
| 859 |
* Automatically create a profile instance. |
| 860 |
""" |
| 861 |
|
| 862 |
ModelClass = serializer.Meta.model |
| 863 |
model_field_info = model_meta.get_field_info(ModelClass) |
| 864 |
|
| 865 |
# Ensure we don't have a writable nested field. For example: |
| 866 |
# |
| 867 |
# class UserSerializer(ModelSerializer): |
| 868 |
# ... |
| 869 |
# profile = ProfileSerializer() |
| 870 |
assert not any( |
| 871 |
isinstance(field, BaseSerializer) and |
| 872 |
(field.source in validated_data) and |
| 873 |
(field.source in model_field_info.relations) and |
| 874 |
isinstance(validated_data[field.source], (list, dict)) |
| 875 |
for field in serializer._writable_fields |
| 876 |
), ( |
| 877 |
'The `.{method_name}()` method does not support writable nested ' |
| 878 |
'fields by default.\nWrite an explicit `.{method_name}()` method for ' |
| 879 |
'serializer `{module}.{class_name}`, or set `read_only=True` on ' |
| 880 |
'nested serializer fields.'.format( |
| 881 |
method_name=method_name, |
| 882 |
module=serializer.__class__.__module__, |
| 883 |
class_name=serializer.__class__.__name__ |
| 884 |
) |
| 885 |
) |
| 886 |
|
| 887 |
# Ensure we don't have a writable dotted-source field. For example: |
| 888 |
# |
| 889 |
# class UserSerializer(ModelSerializer): |
| 890 |
# ... |
| 891 |
# address = serializer.CharField('profile.address') |
| 892 |
# |
| 893 |
# Though, non-relational fields (e.g., JSONField) are acceptable. For example: |
| 894 |
# |
| 895 |
# class NonRelationalPersonModel(models.Model): |
| 896 |
# profile = JSONField() |
| 897 |
# |
| 898 |
# class UserSerializer(ModelSerializer): |
| 899 |
# ... |
| 900 |
# address = serializer.CharField('profile.address') |
| 901 |
assert not any( |
| 902 |
len(field.source_attrs) > 1 and |
| 903 |
(field.source_attrs[0] in validated_data) and |
| 904 |
(field.source_attrs[0] in model_field_info.relations) and |
| 905 |
isinstance(validated_data[field.source_attrs[0]], (list, dict)) |
| 906 |
for field in serializer._writable_fields |
| 907 |
), ( |
| 908 |
'The `.{method_name}()` method does not support writable dotted-source ' |
| 909 |
'fields by default.\nWrite an explicit `.{method_name}()` method for ' |
| 910 |
'serializer `{module}.{class_name}`, or set `read_only=True` on ' |
| 911 |
'dotted-source serializer fields.'.format( |
| 912 |
method_name=method_name, |
| 913 |
module=serializer.__class__.__module__, |
| 914 |
class_name=serializer.__class__.__name__ |
| 915 |
) |
| 916 |
) |
| 917 |
|
| 918 |
|
| 919 |
class ModelSerializer(Serializer): |
| 920 |
""" |
| 921 |
A `ModelSerializer` is just a regular `Serializer`, except that: |
| 922 |
|
| 923 |
* A set of default fields are automatically populated. |
| 924 |
* A set of default validators are automatically populated. |
| 925 |
* Default `.create()` and `.update()` implementations are provided. |
| 926 |
|
| 927 |
The process of automatically determining a set of serializer fields |
| 928 |
based on the model fields is reasonably complex, but you almost certainly |
| 929 |
don't need to dig into the implementation. |
| 930 |
|
| 931 |
If the `ModelSerializer` class *doesn't* generate the set of fields that |
| 932 |
you need you should either declare the extra/differing fields explicitly on |
| 933 |
the serializer class, or simply use a `Serializer` class. |
| 934 |
""" |
| 935 |
serializer_field_mapping = { |
| 936 |
models.AutoField: IntegerField, |
| 937 |
models.BigAutoField: BigIntegerField, |
| 938 |
models.BigIntegerField: BigIntegerField, |
| 939 |
models.BooleanField: BooleanField, |
| 940 |
models.CharField: CharField, |
| 941 |
models.CommaSeparatedIntegerField: CharField, |
| 942 |
models.DateField: DateField, |
| 943 |
models.DateTimeField: DateTimeField, |
| 944 |
models.DecimalField: DecimalField, |
| 945 |
models.DurationField: DurationField, |
| 946 |
models.EmailField: EmailField, |
| 947 |
models.Field: ModelField, |
| 948 |
models.FileField: FileField, |
| 949 |
models.FloatField: FloatField, |
| 950 |
models.ImageField: ImageField, |
| 951 |
models.IntegerField: IntegerField, |
| 952 |
models.NullBooleanField: BooleanField, |
| 953 |
models.PositiveIntegerField: IntegerField, |
| 954 |
models.PositiveSmallIntegerField: IntegerField, |
| 955 |
models.SlugField: SlugField, |
| 956 |
models.SmallIntegerField: IntegerField, |
| 957 |
models.TextField: CharField, |
| 958 |
models.TimeField: TimeField, |
| 959 |
models.URLField: URLField, |
| 960 |
models.UUIDField: UUIDField, |
| 961 |
models.GenericIPAddressField: IPAddressField, |
| 962 |
models.FilePathField: FilePathField, |
| 963 |
} |
| 964 |
if hasattr(models, 'JSONField'): |
| 965 |
serializer_field_mapping[models.JSONField] = JSONField |
| 966 |
if postgres_fields: |
| 967 |
serializer_field_mapping[postgres_fields.HStoreField] = HStoreField |
| 968 |
serializer_field_mapping[postgres_fields.ArrayField] = ListField |
| 969 |
serializer_field_mapping[postgres_fields.JSONField] = JSONField |
| 970 |
serializer_related_field = PrimaryKeyRelatedField |
| 971 |
serializer_related_to_field = SlugRelatedField |
| 972 |
serializer_url_field = HyperlinkedIdentityField |
| 973 |
serializer_choice_field = ChoiceField |
| 974 |
|
| 975 |
# The field name for hyperlinked identity fields. Defaults to 'url'. |
| 976 |
# You can modify this using the API setting. |
| 977 |
# |
| 978 |
# Note that if you instead need modify this on a per-serializer basis, |
| 979 |
# you'll also need to ensure you update the `create` method on any generic |
| 980 |
# views, to correctly handle the 'Location' response header for |
| 981 |
# "HTTP 201 Created" responses. |
| 982 |
url_field_name = None |
| 983 |
|
| 984 |
# Default `create` and `update` behavior... |
| 985 |
def create(self, validated_data): |
| 986 |
""" |
| 987 |
We have a bit of extra checking around this in order to provide |
| 988 |
descriptive messages when something goes wrong, but this method is |
| 989 |
essentially just: |
| 990 |
|
| 991 |
return ExampleModel.objects.create(**validated_data) |
| 992 |
|
| 993 |
If there are many to many fields present on the instance then they |
| 994 |
cannot be set until the model is instantiated, in which case the |
| 995 |
implementation is like so: |
| 996 |
|
| 997 |
example_relationship = validated_data.pop('example_relationship') |
| 998 |
instance = ExampleModel.objects.create(**validated_data) |
| 999 |
instance.example_relationship = example_relationship |
| 1000 |
return instance |
| 1001 |
|
| 1002 |
The default implementation also does not handle nested relationships. |
| 1003 |
If you want to support writable nested relationships you'll need |
| 1004 |
to write an explicit `.create()` method. |
| 1005 |
""" |
| 1006 |
raise_errors_on_nested_writes('create', self, validated_data) |
| 1007 |
|
| 1008 |
ModelClass = self.Meta.model |
| 1009 |
|
| 1010 |
# Remove many-to-many relationships from validated_data. |
| 1011 |
# They are not valid arguments to the default `.create()` method, |
| 1012 |
# as they require that the instance has already been saved. |
| 1013 |
info = model_meta.get_field_info(ModelClass) |
| 1014 |
many_to_many = {} |
| 1015 |
for field_name, relation_info in info.relations.items(): |
| 1016 |
if relation_info.to_many and (field_name in validated_data): |
| 1017 |
many_to_many[field_name] = validated_data.pop(field_name) |
| 1018 |
|
| 1019 |
try: |
| 1020 |
instance = ModelClass._default_manager.create(**validated_data) |
| 1021 |
except TypeError: |
| 1022 |
tb = traceback.format_exc() |
| 1023 |
msg = ( |
| 1024 |
'Got a `TypeError` when calling `%s.%s.create()`. ' |
| 1025 |
'This may be because you have a writable field on the ' |
| 1026 |
'serializer class that is not a valid argument to ' |
| 1027 |
'`%s.%s.create()`. You may need to make the field ' |
| 1028 |
'read-only, or override the %s.create() method to handle ' |
| 1029 |
'this correctly.\nOriginal exception was:\n %s' % |
| 1030 |
( |
| 1031 |
ModelClass.__name__, |
| 1032 |
ModelClass._default_manager.name, |
| 1033 |
ModelClass.__name__, |
| 1034 |
ModelClass._default_manager.name, |
| 1035 |
self.__class__.__name__, |
| 1036 |
tb |
| 1037 |
) |
| 1038 |
) |
| 1039 |
raise TypeError(msg) |
| 1040 |
|
| 1041 |
# Save many-to-many relationships after the instance is created. |
| 1042 |
if many_to_many: |
| 1043 |
for field_name, value in many_to_many.items(): |
| 1044 |
field = getattr(instance, field_name) |
| 1045 |
field.set(value) |
| 1046 |
|
| 1047 |
return instance |
| 1048 |
|
| 1049 |
def update(self, instance, validated_data): |
| 1050 |
raise_errors_on_nested_writes('update', self, validated_data) |
| 1051 |
info = model_meta.get_field_info(instance) |
| 1052 |
|
| 1053 |
# Simply set each attribute on the instance, and then save it. |
| 1054 |
# Note that unlike `.create()` we don't need to treat many-to-many |
| 1055 |
# relationships as being a special case. During updates we already |
| 1056 |
# have an instance pk for the relationships to be associated with. |
| 1057 |
m2m_fields = [] |
| 1058 |
for attr, value in validated_data.items(): |
| 1059 |
if attr in info.relations and info.relations[attr].to_many: |
| 1060 |
m2m_fields.append((attr, value)) |
| 1061 |
else: |
| 1062 |
setattr(instance, attr, value) |
| 1063 |
|
| 1064 |
instance.save() |
| 1065 |
|
| 1066 |
# Note that many-to-many fields are set after updating instance. |
| 1067 |
# Setting m2m fields triggers signals which could potentially change |
| 1068 |
# updated instance and we do not want it to collide with .update() |
| 1069 |
for attr, value in m2m_fields: |
| 1070 |
field = getattr(instance, attr) |
| 1071 |
field.set(value) |
| 1072 |
|
| 1073 |
return instance |
| 1074 |
|
| 1075 |
# Determine the fields to apply... |
| 1076 |
|
| 1077 |
def get_fields(self): |
| 1078 |
""" |
| 1079 |
Return the dict of field names -> field instances that should be |
| 1080 |
used for `self.fields` when instantiating the serializer. |
| 1081 |
""" |
| 1082 |
if self.url_field_name is None: |
| 1083 |
self.url_field_name = api_settings.URL_FIELD_NAME |
| 1084 |
|
| 1085 |
assert hasattr(self, 'Meta'), ( |
| 1086 |
'Class {serializer_class} missing "Meta" attribute'.format( |
| 1087 |
serializer_class=self.__class__.__name__ |
| 1088 |
) |
| 1089 |
) |
| 1090 |
assert hasattr(self.Meta, 'model'), ( |
| 1091 |
'Class {serializer_class} missing "Meta.model" attribute'.format( |
| 1092 |
serializer_class=self.__class__.__name__ |
| 1093 |
) |
| 1094 |
) |
| 1095 |
if model_meta.is_abstract_model(self.Meta.model): |
| 1096 |
raise ValueError( |
| 1097 |
'Cannot use ModelSerializer with Abstract Models.' |
| 1098 |
) |
| 1099 |
|
| 1100 |
declared_fields = copy.deepcopy(self._declared_fields) |
| 1101 |
model = getattr(self.Meta, 'model') |
| 1102 |
depth = getattr(self.Meta, 'depth', 0) |
| 1103 |
|
| 1104 |
if depth is not None: |
| 1105 |
assert depth >= 0, "'depth' may not be negative." |
| 1106 |
assert depth <= 10, "'depth' may not be greater than 10." |
| 1107 |
|
| 1108 |
# Retrieve metadata about fields & relationships on the model class. |
| 1109 |
info = model_meta.get_field_info(model) |
| 1110 |
field_names = self.get_field_names(declared_fields, info) |
| 1111 |
|
| 1112 |
# Determine any extra field arguments and hidden fields that |
| 1113 |
# should be included |
| 1114 |
extra_kwargs = self.get_extra_kwargs() |
| 1115 |
extra_kwargs, hidden_fields = self.get_uniqueness_extra_kwargs( |
| 1116 |
field_names, declared_fields, extra_kwargs |
| 1117 |
) |
| 1118 |
|
| 1119 |
# Determine the fields that should be included on the serializer. |
| 1120 |
fields = {} |
| 1121 |
|
| 1122 |
# If it's a ManyToMany field, and the default is None, then raises an exception to prevent exceptions on .set() |
| 1123 |
for field_name in declared_fields.keys(): |
| 1124 |
if field_name in info.relations and info.relations[field_name].to_many and declared_fields[field_name].default is None: |
| 1125 |
raise ValueError( |
| 1126 |
f"The field '{field_name}' on serializer '{self.__class__.__name__}' is a ManyToMany field and cannot have a default value of None." |
| 1127 |
) |
| 1128 |
|
| 1129 |
for field_name in field_names: |
| 1130 |
# If the field is explicitly declared on the class then use that. |
| 1131 |
if field_name in declared_fields: |
| 1132 |
fields[field_name] = declared_fields[field_name] |
| 1133 |
continue |
| 1134 |
|
| 1135 |
extra_field_kwargs = extra_kwargs.get(field_name, {}) |
| 1136 |
source = extra_field_kwargs.get('source', '*') |
| 1137 |
if source == '*': |
| 1138 |
source = field_name |
| 1139 |
|
| 1140 |
# Determine the serializer field class and keyword arguments. |
| 1141 |
field_class, field_kwargs = self.build_field( |
| 1142 |
source, info, model, depth |
| 1143 |
) |
| 1144 |
|
| 1145 |
# Include any kwargs defined in `Meta.extra_kwargs` |
| 1146 |
field_kwargs = self.include_extra_kwargs( |
| 1147 |
field_kwargs, extra_field_kwargs |
| 1148 |
) |
| 1149 |
|
| 1150 |
# Create the serializer field. |
| 1151 |
fields[field_name] = field_class(**field_kwargs) |
| 1152 |
|
| 1153 |
# Add in any hidden fields. |
| 1154 |
fields.update(hidden_fields) |
| 1155 |
|
| 1156 |
return fields |
| 1157 |
|
| 1158 |
# Methods for determining the set of field names to include... |
| 1159 |
|
| 1160 |
def get_field_names(self, declared_fields, info): |
| 1161 |
""" |
| 1162 |
Returns the list of all field names that should be created when |
| 1163 |
instantiating this serializer class. This is based on the default |
| 1164 |
set of fields, but also takes into account the `Meta.fields` or |
| 1165 |
`Meta.exclude` options if they have been specified. |
| 1166 |
""" |
| 1167 |
fields = getattr(self.Meta, 'fields', None) |
| 1168 |
exclude = getattr(self.Meta, 'exclude', None) |
| 1169 |
|
| 1170 |
if fields and fields != ALL_FIELDS and not isinstance(fields, (list, tuple)): |
| 1171 |
raise TypeError( |
| 1172 |
'The `fields` option must be a list or tuple or "__all__". ' |
| 1173 |
'Got %s.' % type(fields).__name__ |
| 1174 |
) |
| 1175 |
|
| 1176 |
if exclude and not isinstance(exclude, (list, tuple)): |
| 1177 |
raise TypeError( |
| 1178 |
'The `exclude` option must be a list or tuple. Got %s.' % |
| 1179 |
type(exclude).__name__ |
| 1180 |
) |
| 1181 |
|
| 1182 |
assert not (fields and exclude), ( |
| 1183 |
"Cannot set both 'fields' and 'exclude' options on " |
| 1184 |
"serializer {serializer_class}.".format( |
| 1185 |
serializer_class=self.__class__.__name__ |
| 1186 |
) |
| 1187 |
) |
| 1188 |
|
| 1189 |
assert not (fields is None and exclude is None), ( |
| 1190 |
"Creating a ModelSerializer without either the 'fields' attribute " |
| 1191 |
"or the 'exclude' attribute has been deprecated since 3.3.0, " |
| 1192 |
"and is now disallowed. Add an explicit fields = '__all__' to the " |
| 1193 |
"{serializer_class} serializer.".format( |
| 1194 |
serializer_class=self.__class__.__name__ |
| 1195 |
), |
| 1196 |
) |
| 1197 |
|
| 1198 |
if fields == ALL_FIELDS: |
| 1199 |
fields = None |
| 1200 |
|
| 1201 |
if fields is not None: |
| 1202 |
# Ensure that all declared fields have also been included in the |
| 1203 |
# `Meta.fields` option. |
| 1204 |
|
| 1205 |
# Do not require any fields that are declared in a parent class, |
| 1206 |
# in order to allow serializer subclasses to only include |
| 1207 |
# a subset of fields. |
| 1208 |
required_field_names = set(declared_fields) |
| 1209 |
for cls in self.__class__.__bases__: |
| 1210 |
required_field_names -= set(getattr(cls, '_declared_fields', [])) |
| 1211 |
|
| 1212 |
for field_name in required_field_names: |
| 1213 |
assert field_name in fields, ( |
| 1214 |
"The field '{field_name}' was declared on serializer " |
| 1215 |
"{serializer_class}, but has not been included in the " |
| 1216 |
"'fields' option.".format( |
| 1217 |
field_name=field_name, |
| 1218 |
serializer_class=self.__class__.__name__ |
| 1219 |
) |
| 1220 |
) |
| 1221 |
return fields |
| 1222 |
|
| 1223 |
# Use the default set of field names if `Meta.fields` is not specified. |
| 1224 |
fields = self.get_default_field_names(declared_fields, info) |
| 1225 |
|
| 1226 |
if exclude is not None: |
| 1227 |
# If `Meta.exclude` is included, then remove those fields. |
| 1228 |
for field_name in exclude: |
| 1229 |
assert field_name not in self._declared_fields, ( |
| 1230 |
"Cannot both declare the field '{field_name}' and include " |
| 1231 |
"it in the {serializer_class} 'exclude' option. Remove the " |
| 1232 |
"field or, if inherited from a parent serializer, disable " |
| 1233 |
"with `{field_name} = None`." |
| 1234 |
.format( |
| 1235 |
field_name=field_name, |
| 1236 |
serializer_class=self.__class__.__name__ |
| 1237 |
) |
| 1238 |
) |
| 1239 |
|
| 1240 |
assert field_name in fields, ( |
| 1241 |
"The field '{field_name}' was included on serializer " |
| 1242 |
"{serializer_class} in the 'exclude' option, but does " |
| 1243 |
"not match any model field.".format( |
| 1244 |
field_name=field_name, |
| 1245 |
serializer_class=self.__class__.__name__ |
| 1246 |
) |
| 1247 |
) |
| 1248 |
fields.remove(field_name) |
| 1249 |
|
| 1250 |
return fields |
| 1251 |
|
| 1252 |
def get_default_field_names(self, declared_fields, model_info): |
| 1253 |
""" |
| 1254 |
Return the default list of field names that will be used if the |
| 1255 |
`Meta.fields` option is not specified. |
| 1256 |
""" |
| 1257 |
return ( |
| 1258 |
[model_info.pk.name] + |
| 1259 |
list(declared_fields) + |
| 1260 |
list(model_info.fields) + |
| 1261 |
list(model_info.forward_relations) |
| 1262 |
) |
| 1263 |
|
| 1264 |
# Methods for constructing serializer fields... |
| 1265 |
|
| 1266 |
def build_field(self, field_name, info, model_class, nested_depth): |
| 1267 |
""" |
| 1268 |
Return a two tuple of (cls, kwargs) to build a serializer field with. |
| 1269 |
""" |
| 1270 |
if field_name in info.fields_and_pk: |
| 1271 |
model_field = info.fields_and_pk[field_name] |
| 1272 |
return self.build_standard_field(field_name, model_field) |
| 1273 |
|
| 1274 |
elif field_name in info.relations: |
| 1275 |
relation_info = info.relations[field_name] |
| 1276 |
if not nested_depth: |
| 1277 |
return self.build_relational_field(field_name, relation_info) |
| 1278 |
else: |
| 1279 |
return self.build_nested_field(field_name, relation_info, nested_depth) |
| 1280 |
|
| 1281 |
elif hasattr(model_class, field_name): |
| 1282 |
return self.build_property_field(field_name, model_class) |
| 1283 |
|
| 1284 |
elif field_name == self.url_field_name: |
| 1285 |
return self.build_url_field(field_name, model_class) |
| 1286 |
|
| 1287 |
return self.build_unknown_field(field_name, model_class) |
| 1288 |
|
| 1289 |
def build_standard_field(self, field_name, model_field): |
| 1290 |
""" |
| 1291 |
Create regular model fields. |
| 1292 |
""" |
| 1293 |
field_mapping = ClassLookupDict(self.serializer_field_mapping) |
| 1294 |
|
| 1295 |
field_class = field_mapping[model_field] |
| 1296 |
field_kwargs = get_field_kwargs(field_name, model_field) |
| 1297 |
|
| 1298 |
# Special case to handle when a OneToOneField is also the primary key |
| 1299 |
if model_field.one_to_one and model_field.primary_key: |
| 1300 |
field_class = self.serializer_related_field |
| 1301 |
field_kwargs['queryset'] = model_field.related_model.objects |
| 1302 |
|
| 1303 |
if 'choices' in field_kwargs: |
| 1304 |
# Fields with choices get coerced into `ChoiceField` |
| 1305 |
# instead of using their regular typed field. |
| 1306 |
field_class = self.serializer_choice_field |
| 1307 |
# Some model fields may introduce kwargs that would not be valid |
| 1308 |
# for the choice field. We need to strip these out. |
| 1309 |
# Eg. models.DecimalField(max_digits=3, decimal_places=1, choices=DECIMAL_CHOICES) |
| 1310 |
valid_kwargs = { |
| 1311 |
'read_only', 'write_only', |
| 1312 |
'required', 'default', 'initial', 'source', |
| 1313 |
'label', 'help_text', 'style', |
| 1314 |
'error_messages', 'validators', 'allow_null', 'allow_blank', |
| 1315 |
'choices' |
| 1316 |
} |
| 1317 |
for key in list(field_kwargs): |
| 1318 |
if key not in valid_kwargs: |
| 1319 |
field_kwargs.pop(key) |
| 1320 |
|
| 1321 |
if not issubclass(field_class, ModelField): |
| 1322 |
# `model_field` is only valid for the fallback case of |
| 1323 |
# `ModelField`, which is used when no other typed field |
| 1324 |
# matched to the model field. |
| 1325 |
field_kwargs.pop('model_field', None) |
| 1326 |
|
| 1327 |
if not issubclass(field_class, CharField) and not issubclass(field_class, ChoiceField): |
| 1328 |
# `allow_blank` is only valid for textual fields. |
| 1329 |
field_kwargs.pop('allow_blank', None) |
| 1330 |
|
| 1331 |
is_django_jsonfield = hasattr(models, 'JSONField') and isinstance(model_field, models.JSONField) |
| 1332 |
if (postgres_fields and isinstance(model_field, postgres_fields.JSONField)) or is_django_jsonfield: |
| 1333 |
# Populate the `encoder` argument of `JSONField` instances generated |
| 1334 |
# for the model `JSONField`. |
| 1335 |
field_kwargs['encoder'] = getattr(model_field, 'encoder', None) |
| 1336 |
if is_django_jsonfield: |
| 1337 |
field_kwargs['decoder'] = getattr(model_field, 'decoder', None) |
| 1338 |
|
| 1339 |
if postgres_fields and isinstance(model_field, postgres_fields.ArrayField): |
| 1340 |
# Populate the `child` argument on `ListField` instances generated |
| 1341 |
# for the PostgreSQL specific `ArrayField`. |
| 1342 |
child_model_field = model_field.base_field |
| 1343 |
child_field_class, child_field_kwargs = self.build_standard_field( |
| 1344 |
'child', child_model_field |
| 1345 |
) |
| 1346 |
field_kwargs['child'] = child_field_class(**child_field_kwargs) |
| 1347 |
|
| 1348 |
return field_class, field_kwargs |
| 1349 |
|
| 1350 |
def build_relational_field(self, field_name, relation_info): |
| 1351 |
""" |
| 1352 |
Create fields for forward and reverse relationships. |
| 1353 |
""" |
| 1354 |
field_class = self.serializer_related_field |
| 1355 |
field_kwargs = get_relation_kwargs(field_name, relation_info) |
| 1356 |
|
| 1357 |
to_field = field_kwargs.pop('to_field', None) |
| 1358 |
if to_field and not relation_info.reverse and not relation_info.related_model._meta.get_field(to_field).primary_key: |
| 1359 |
field_kwargs['slug_field'] = to_field |
| 1360 |
field_class = self.serializer_related_to_field |
| 1361 |
|
| 1362 |
# `view_name` is only valid for hyperlinked relationships. |
| 1363 |
if not issubclass(field_class, HyperlinkedRelatedField): |
| 1364 |
field_kwargs.pop('view_name', None) |
| 1365 |
|
| 1366 |
return field_class, field_kwargs |
| 1367 |
|
| 1368 |
def build_nested_field(self, field_name, relation_info, nested_depth): |
| 1369 |
""" |
| 1370 |
Create nested fields for forward and reverse relationships. |
| 1371 |
""" |
| 1372 |
class NestedSerializer(ModelSerializer): |
| 1373 |
class Meta: |
| 1374 |
model = relation_info.related_model |
| 1375 |
depth = nested_depth - 1 |
| 1376 |
fields = '__all__' |
| 1377 |
|
| 1378 |
field_class = NestedSerializer |
| 1379 |
field_kwargs = get_nested_relation_kwargs(relation_info) |
| 1380 |
|
| 1381 |
return field_class, field_kwargs |
| 1382 |
|
| 1383 |
def build_property_field(self, field_name, model_class): |
| 1384 |
""" |
| 1385 |
Create a read only field for model methods and properties. |
| 1386 |
""" |
| 1387 |
field_class = ReadOnlyField |
| 1388 |
field_kwargs = {} |
| 1389 |
|
| 1390 |
return field_class, field_kwargs |
| 1391 |
|
| 1392 |
def build_url_field(self, field_name, model_class): |
| 1393 |
""" |
| 1394 |
Create a field representing the object's own URL. |
| 1395 |
""" |
| 1396 |
field_class = self.serializer_url_field |
| 1397 |
field_kwargs = get_url_kwargs(model_class) |
| 1398 |
|
| 1399 |
return field_class, field_kwargs |
| 1400 |
|
| 1401 |
def build_unknown_field(self, field_name, model_class): |
| 1402 |
""" |
| 1403 |
Raise an error on any unknown fields. |
| 1404 |
""" |
| 1405 |
raise ImproperlyConfigured( |
| 1406 |
'Field name `%s` is not valid for model `%s` in `%s.%s`.' % |
| 1407 |
(field_name, model_class.__name__, self.__class__.__module__, self.__class__.__name__) |
| 1408 |
) |
| 1409 |
|
| 1410 |
def include_extra_kwargs(self, kwargs, extra_kwargs): |
| 1411 |
""" |
| 1412 |
Include any 'extra_kwargs' that have been included for this field, |
| 1413 |
possibly removing any incompatible existing keyword arguments. |
| 1414 |
""" |
| 1415 |
if extra_kwargs.get('read_only', False): |
| 1416 |
for attr in [ |
| 1417 |
'required', 'default', 'allow_blank', 'min_length', |
| 1418 |
'max_length', 'min_value', 'max_value', 'validators', 'queryset' |
| 1419 |
]: |
| 1420 |
kwargs.pop(attr, None) |
| 1421 |
|
| 1422 |
if extra_kwargs.get('default') and kwargs.get('required') is False: |
| 1423 |
kwargs.pop('required') |
| 1424 |
|
| 1425 |
if extra_kwargs.get('read_only', kwargs.get('read_only', False)): |
| 1426 |
extra_kwargs.pop('required', None) # Read only fields should always omit the 'required' argument. |
| 1427 |
|
| 1428 |
kwargs.update(extra_kwargs) |
| 1429 |
|
| 1430 |
return kwargs |
| 1431 |
|
| 1432 |
# Methods for determining additional keyword arguments to apply... |
| 1433 |
|
| 1434 |
def get_extra_kwargs(self): |
| 1435 |
""" |
| 1436 |
Return a dictionary mapping field names to a dictionary of |
| 1437 |
additional keyword arguments. |
| 1438 |
""" |
| 1439 |
extra_kwargs = copy.deepcopy(getattr(self.Meta, 'extra_kwargs', {})) |
| 1440 |
|
| 1441 |
read_only_fields = getattr(self.Meta, 'read_only_fields', None) |
| 1442 |
if read_only_fields is not None: |
| 1443 |
if not isinstance(read_only_fields, (list, tuple)): |
| 1444 |
raise TypeError( |
| 1445 |
'The `read_only_fields` option must be a list or tuple. ' |
| 1446 |
'Got %s.' % type(read_only_fields).__name__ |
| 1447 |
) |
| 1448 |
for field_name in read_only_fields: |
| 1449 |
kwargs = extra_kwargs.get(field_name, {}) |
| 1450 |
kwargs['read_only'] = True |
| 1451 |
extra_kwargs[field_name] = kwargs |
| 1452 |
|
| 1453 |
else: |
| 1454 |
# Guard against the possible misspelling `readonly_fields` (used |
| 1455 |
# by the Django admin and others). |
| 1456 |
assert not hasattr(self.Meta, 'readonly_fields'), ( |
| 1457 |
'Serializer `%s.%s` has field `readonly_fields`; ' |
| 1458 |
'the correct spelling for the option is `read_only_fields`.' % |
| 1459 |
(self.__class__.__module__, self.__class__.__name__) |
| 1460 |
) |
| 1461 |
|
| 1462 |
return extra_kwargs |
| 1463 |
|
| 1464 |
def get_unique_together_constraints(self, model): |
| 1465 |
""" |
| 1466 |
Returns iterator of (fields, queryset, condition_fields, condition, nulls_distinct), |
| 1467 |
each entry describes an unique together constraint on `fields` in `queryset` |
| 1468 |
with respect of constraint's `condition` and `nulls_distinct` option. |
| 1469 |
""" |
| 1470 |
for parent_class in [model] + list(model._meta.parents): |
| 1471 |
for unique_together in parent_class._meta.unique_together: |
| 1472 |
yield unique_together, model._default_manager, [], None, None |
| 1473 |
for constraint in parent_class._meta.constraints: |
| 1474 |
if isinstance(constraint, models.UniqueConstraint) and len(constraint.fields) > 1: |
| 1475 |
if constraint.condition is None: |
| 1476 |
condition_fields = [] |
| 1477 |
else: |
| 1478 |
condition_fields = list(constraint.condition.referenced_base_fields) |
| 1479 |
yield ( |
| 1480 |
constraint.fields, |
| 1481 |
model._default_manager, |
| 1482 |
condition_fields, |
| 1483 |
constraint.condition, |
| 1484 |
constraint.nulls_distinct, |
| 1485 |
) |
| 1486 |
|
| 1487 |
def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs): |
| 1488 |
""" |
| 1489 |
Return any additional field options that need to be included as a |
| 1490 |
result of uniqueness constraints on the model. This is returned as |
| 1491 |
a two-tuple of: |
| 1492 |
|
| 1493 |
('dict of updated extra kwargs', 'mapping of hidden fields') |
| 1494 |
""" |
| 1495 |
if getattr(self.Meta, 'validators', None) is not None: |
| 1496 |
return (extra_kwargs, {}) |
| 1497 |
|
| 1498 |
model = getattr(self.Meta, 'model') |
| 1499 |
model_fields = self._get_model_fields( |
| 1500 |
field_names, declared_fields, extra_kwargs |
| 1501 |
) |
| 1502 |
|
| 1503 |
# Determine if we need any additional `HiddenField` or extra keyword |
| 1504 |
# arguments to deal with `unique_for` dates that are required to |
| 1505 |
# be in the input data in order to validate it. |
| 1506 |
unique_constraint_names = set() |
| 1507 |
|
| 1508 |
for model_field in model_fields.values(): |
| 1509 |
# Include each of the `unique_for_*` field names. |
| 1510 |
unique_constraint_names |= {model_field.unique_for_date, model_field.unique_for_month, |
| 1511 |
model_field.unique_for_year} |
| 1512 |
|
| 1513 |
unique_constraint_names -= {None} |
| 1514 |
model_fields_names = set(model_fields.keys()) |
| 1515 |
|
| 1516 |
# Include each of the `unique_together` and `UniqueConstraint` field names, |
| 1517 |
# so long as all the field names are included on the serializer. |
| 1518 |
for unique_together_list, queryset, condition_fields, condition, nulls_distinct in self.get_unique_together_constraints(model): |
| 1519 |
unique_together_list_and_condition_fields = set(unique_together_list) | set(condition_fields) |
| 1520 |
if model_fields_names.issuperset(unique_together_list_and_condition_fields): |
| 1521 |
unique_constraint_names |= unique_together_list_and_condition_fields |
| 1522 |
|
| 1523 |
# Now we have all the field names that have uniqueness constraints |
| 1524 |
# applied, we can add the extra 'required=...' or 'default=...' |
| 1525 |
# arguments that are appropriate to these fields, or add a `HiddenField` for it. |
| 1526 |
hidden_fields = {} |
| 1527 |
uniqueness_extra_kwargs = {} |
| 1528 |
|
| 1529 |
for unique_constraint_name in unique_constraint_names: |
| 1530 |
# Get the model field that is referred too. |
| 1531 |
unique_constraint_field = model._meta.get_field(unique_constraint_name) |
| 1532 |
|
| 1533 |
if getattr(unique_constraint_field, 'auto_now_add', None): |
| 1534 |
default = CreateOnlyDefault(timezone.now) |
| 1535 |
elif getattr(unique_constraint_field, 'auto_now', None): |
| 1536 |
default = timezone.now |
| 1537 |
elif unique_constraint_field.has_default(): |
| 1538 |
default = unique_constraint_field.default |
| 1539 |
elif unique_constraint_field.null: |
| 1540 |
default = None |
| 1541 |
else: |
| 1542 |
default = empty |
| 1543 |
|
| 1544 |
if unique_constraint_name in model_fields: |
| 1545 |
# The corresponding field is present in the serializer |
| 1546 |
if default is empty: |
| 1547 |
uniqueness_extra_kwargs[unique_constraint_name] = {'required': True} |
| 1548 |
else: |
| 1549 |
uniqueness_extra_kwargs[unique_constraint_name] = {'default': default} |
| 1550 |
elif default is not empty: |
| 1551 |
# The corresponding field is not present in the |
| 1552 |
# serializer. We have a default to use for it, so |
| 1553 |
# add in a hidden field that populates it. |
| 1554 |
hidden_fields[unique_constraint_name] = HiddenField(default=default) |
| 1555 |
|
| 1556 |
# Update `extra_kwargs` with any new options. |
| 1557 |
for key, value in uniqueness_extra_kwargs.items(): |
| 1558 |
if key in extra_kwargs: |
| 1559 |
value.update(extra_kwargs[key]) |
| 1560 |
extra_kwargs[key] = value |
| 1561 |
|
| 1562 |
return extra_kwargs, hidden_fields |
| 1563 |
|
| 1564 |
def _get_model_fields(self, field_names, declared_fields, extra_kwargs): |
| 1565 |
""" |
| 1566 |
Returns all the model fields that are being mapped to by fields |
| 1567 |
on the serializer class. |
| 1568 |
Returned as a dict of 'model field name' -> 'model field'. |
| 1569 |
Used internally by `get_uniqueness_field_options`. |
| 1570 |
""" |
| 1571 |
model = getattr(self.Meta, 'model') |
| 1572 |
model_fields = {} |
| 1573 |
|
| 1574 |
for field_name in field_names: |
| 1575 |
if field_name in declared_fields: |
| 1576 |
# If the field is declared on the serializer |
| 1577 |
field = declared_fields[field_name] |
| 1578 |
source = field.source or field_name |
| 1579 |
else: |
| 1580 |
try: |
| 1581 |
source = extra_kwargs[field_name]['source'] |
| 1582 |
except KeyError: |
| 1583 |
source = field_name |
| 1584 |
|
| 1585 |
if '.' in source or source == '*': |
| 1586 |
# Model fields will always have a simple source mapping, |
| 1587 |
# they can't be nested attribute lookups. |
| 1588 |
continue |
| 1589 |
|
| 1590 |
with contextlib.suppress(FieldDoesNotExist): |
| 1591 |
field = model._meta.get_field(source) |
| 1592 |
if isinstance(field, DjangoModelField): |
| 1593 |
model_fields[source] = field |
| 1594 |
|
| 1595 |
return model_fields |
| 1596 |
|
| 1597 |
# Determine the validators to apply... |
| 1598 |
|
| 1599 |
def get_validators(self): |
| 1600 |
""" |
| 1601 |
Determine the set of validators to use when instantiating serializer. |
| 1602 |
""" |
| 1603 |
# If the validators have been declared explicitly then use that. |
| 1604 |
validators = getattr(getattr(self, 'Meta', None), 'validators', None) |
| 1605 |
if validators is not None: |
| 1606 |
return list(validators) |
| 1607 |
|
| 1608 |
# Otherwise use the default set of validators. |
| 1609 |
return ( |
| 1610 |
self.get_unique_together_validators() + |
| 1611 |
self.get_unique_for_date_validators() |
| 1612 |
) |
| 1613 |
|
| 1614 |
def _get_constraint_violation_error_message(self, constraint): |
| 1615 |
""" |
| 1616 |
Returns the violation error message for the UniqueConstraint, |
| 1617 |
or None if the message is the default. |
| 1618 |
""" |
| 1619 |
violation_error_message = constraint.get_violation_error_message() |
| 1620 |
default_error_message = constraint.default_violation_error_message % {"name": constraint.name} |
| 1621 |
if violation_error_message == default_error_message: |
| 1622 |
return None |
| 1623 |
return violation_error_message |
| 1624 |
|
| 1625 |
def get_unique_together_validators(self): |
| 1626 |
""" |
| 1627 |
Determine a default set of validators for any unique_together constraints. |
| 1628 |
""" |
| 1629 |
# The field names we're passing though here only include fields |
| 1630 |
# which may map onto a model field. Any dotted field name lookups |
| 1631 |
# cannot map to a field, and must be a traversal, so we're not |
| 1632 |
# including those. |
| 1633 |
field_sources = { |
| 1634 |
field.field_name: field.source for field in self._writable_fields |
| 1635 |
if (field.source != '*') and ('.' not in field.source) |
| 1636 |
} |
| 1637 |
|
| 1638 |
# Special Case: Add read_only fields with defaults. |
| 1639 |
field_sources.update({ |
| 1640 |
field.field_name: field.source for field in self.fields.values() |
| 1641 |
if (field.read_only) and (field.default != empty) and (field.source != '*') and ('.' not in field.source) |
| 1642 |
}) |
| 1643 |
|
| 1644 |
# Invert so we can find the serializer field names that correspond to |
| 1645 |
# the model field names in the unique_together sets. This also allows |
| 1646 |
# us to check that multiple fields don't map to the same source. |
| 1647 |
source_map = defaultdict(list) |
| 1648 |
for name, source in field_sources.items(): |
| 1649 |
source_map[source].append(name) |
| 1650 |
|
| 1651 |
unique_constraint_by_fields = { |
| 1652 |
constraint.fields: constraint |
| 1653 |
for model_cls in (*self.Meta.model._meta.parents, self.Meta.model) |
| 1654 |
for constraint in model_cls._meta.constraints |
| 1655 |
if isinstance(constraint, models.UniqueConstraint) |
| 1656 |
} |
| 1657 |
|
| 1658 |
# Note that we make sure to check `unique_together` both on the |
| 1659 |
# base model class, but also on any parent classes. |
| 1660 |
validators = [] |
| 1661 |
for unique_together, queryset, condition_fields, condition, nulls_distinct in self.get_unique_together_constraints(self.Meta.model): |
| 1662 |
# Skip if serializer does not map to all unique together sources |
| 1663 |
unique_together_and_condition_fields = set(unique_together) | set(condition_fields) |
| 1664 |
if not set(source_map).issuperset(unique_together_and_condition_fields): |
| 1665 |
continue |
| 1666 |
|
| 1667 |
for source in unique_together_and_condition_fields: |
| 1668 |
assert len(source_map[source]) == 1, ( |
| 1669 |
"Unable to create `UniqueTogetherValidator` for " |
| 1670 |
"`{model}.{field}` as `{serializer}` has multiple " |
| 1671 |
"fields ({fields}) that map to this model field. " |
| 1672 |
"Either remove the extra fields, or override " |
| 1673 |
"`Meta.validators` with a `UniqueTogetherValidator` " |
| 1674 |
"using the desired field names." |
| 1675 |
.format( |
| 1676 |
model=self.Meta.model.__name__, |
| 1677 |
serializer=self.__class__.__name__, |
| 1678 |
field=source, |
| 1679 |
fields=', '.join(source_map[source]), |
| 1680 |
) |
| 1681 |
) |
| 1682 |
|
| 1683 |
field_names = tuple(source_map[f][0] for f in unique_together) |
| 1684 |
|
| 1685 |
constraint = unique_constraint_by_fields.get(tuple(unique_together)) |
| 1686 |
violation_error_message = self._get_constraint_violation_error_message(constraint) if constraint else None |
| 1687 |
|
| 1688 |
validator = UniqueTogetherValidator( |
| 1689 |
queryset=queryset, |
| 1690 |
fields=field_names, |
| 1691 |
condition_fields=tuple(source_map[f][0] for f in condition_fields), |
| 1692 |
condition=condition, |
| 1693 |
message=violation_error_message, |
| 1694 |
code=getattr(constraint, 'violation_error_code', None), |
| 1695 |
nulls_distinct=nulls_distinct, |
| 1696 |
) |
| 1697 |
validators.append(validator) |
| 1698 |
return validators |
| 1699 |
|
| 1700 |
def get_unique_for_date_validators(self): |
| 1701 |
""" |
| 1702 |
Determine a default set of validators for the following constraints: |
| 1703 |
|
| 1704 |
* unique_for_date |
| 1705 |
* unique_for_month |
| 1706 |
* unique_for_year |
| 1707 |
""" |
| 1708 |
info = model_meta.get_field_info(self.Meta.model) |
| 1709 |
default_manager = self.Meta.model._default_manager |
| 1710 |
field_names = [field.source for field in self.fields.values()] |
| 1711 |
|
| 1712 |
validators = [] |
| 1713 |
|
| 1714 |
for field_name, field in info.fields_and_pk.items(): |
| 1715 |
if field.unique_for_date and field_name in field_names: |
| 1716 |
validator = UniqueForDateValidator( |
| 1717 |
queryset=default_manager, |
| 1718 |
field=field_name, |
| 1719 |
date_field=field.unique_for_date |
| 1720 |
) |
| 1721 |
validators.append(validator) |
| 1722 |
|
| 1723 |
if field.unique_for_month and field_name in field_names: |
| 1724 |
validator = UniqueForMonthValidator( |
| 1725 |
queryset=default_manager, |
| 1726 |
field=field_name, |
| 1727 |
date_field=field.unique_for_month |
| 1728 |
) |
| 1729 |
validators.append(validator) |
| 1730 |
|
| 1731 |
if field.unique_for_year and field_name in field_names: |
| 1732 |
validator = UniqueForYearValidator( |
| 1733 |
queryset=default_manager, |
| 1734 |
field=field_name, |
| 1735 |
date_field=field.unique_for_year |
| 1736 |
) |
| 1737 |
validators.append(validator) |
| 1738 |
|
| 1739 |
return validators |
| 1740 |
|
| 1741 |
|
| 1742 |
class HyperlinkedModelSerializer(ModelSerializer): |
| 1743 |
""" |
| 1744 |
A type of `ModelSerializer` that uses hyperlinked relationships instead |
| 1745 |
of primary key relationships. Specifically: |
| 1746 |
|
| 1747 |
* A 'url' field is included instead of the 'id' field. |
| 1748 |
* Relationships to other instances are hyperlinks, instead of primary keys. |
| 1749 |
""" |
| 1750 |
serializer_related_field = HyperlinkedRelatedField |
| 1751 |
|
| 1752 |
def get_default_field_names(self, declared_fields, model_info): |
| 1753 |
""" |
| 1754 |
Return the default list of field names that will be used if the |
| 1755 |
`Meta.fields` option is not specified. |
| 1756 |
""" |
| 1757 |
return ( |
| 1758 |
[self.url_field_name] + |
| 1759 |
list(declared_fields) + |
| 1760 |
list(model_info.fields) + |
| 1761 |
list(model_info.forward_relations) |
| 1762 |
) |
| 1763 |
|
| 1764 |
def build_nested_field(self, field_name, relation_info, nested_depth): |
| 1765 |
""" |
| 1766 |
Create nested fields for forward and reverse relationships. |
| 1767 |
""" |
| 1768 |
class NestedSerializer(HyperlinkedModelSerializer): |
| 1769 |
class Meta: |
| 1770 |
model = relation_info.related_model |
| 1771 |
depth = nested_depth - 1 |
| 1772 |
fields = '__all__' |
| 1773 |
|
| 1774 |
field_class = NestedSerializer |
| 1775 |
field_kwargs = get_nested_relation_kwargs(relation_info) |
| 1776 |
|
| 1777 |
return field_class, field_kwargs |