Debian Codegraph @

rest_framework/relations.py

raw
1 import contextlib
2 import sys
3 from operator import attrgetter
4 from urllib import parse
5
6 from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
7 from django.db.models import Manager
8 from django.db.models.query import QuerySet
9 from django.urls import NoReverseMatch, Resolver404, get_script_prefix, resolve
10 from django.utils.encoding import smart_str, uri_to_iri
11 from django.utils.translation import gettext_lazy as _
12
13 from rest_framework.fields import (
14 Field, SkipField, empty, get_attribute, is_simple_callable, iter_options
15 )
16 from rest_framework.reverse import reverse
17 from rest_framework.settings import api_settings
18 from rest_framework.utils import html
19
20
21 def method_overridden(method_name, klass, instance):
22 """
23 Determine if a method has been overridden.
24 """
25 method = getattr(klass, method_name)
26 default_method = getattr(method, '__func__', method) # Python 3 compat
27 return default_method is not getattr(instance, method_name).__func__
28
29
30 class ObjectValueError(ValueError):
31 """
32 Raised when `queryset.get()` failed due to an underlying `ValueError`.
33 Wrapping prevents calling code conflating this with unrelated errors.
34 """
35
36
37 class ObjectTypeError(TypeError):
38 """
39 Raised when `queryset.get()` failed due to an underlying `TypeError`.
40 Wrapping prevents calling code conflating this with unrelated errors.
41 """
42
43
44 class Hyperlink(str):
45 """
46 A string like object that additionally has an associated name.
47 We use this for hyperlinked URLs that may render as a named link
48 in some contexts, or render as a plain URL in others.
49 """
50 def __new__(cls, url, obj):
51 ret = super().__new__(cls, url)
52 ret.obj = obj
53 return ret
54
55 def __getnewargs__(self):
56 return (str(self), self.name)
57
58 @property
59 def name(self):
60 # This ensures that we only called `__str__` lazily,
61 # as in some cases calling __str__ on a model instances *might*
62 # involve a database lookup.
63 return str(self.obj)
64
65 is_hyperlink = True
66
67
68 class PKOnlyObject:
69 """
70 This is a mock object, used for when we only need the pk of the object
71 instance, but still want to return an object with a .pk attribute,
72 in order to keep the same interface as a regular model instance.
73 """
74
75 def __init__(self, pk):
76 self.pk = pk
77
78 def __str__(self):
79 return "%s" % self.pk
80
81
82 # We assume that 'validators' are intended for the child serializer,
83 # rather than the parent serializer.
84 MANY_RELATION_KWARGS = (
85 'read_only', 'write_only', 'required', 'default', 'initial', 'source',
86 'label', 'help_text', 'style', 'error_messages', 'allow_empty',
87 'html_cutoff', 'html_cutoff_text'
88 )
89
90
91 class RelatedField(Field):
92 queryset = None
93 html_cutoff = None
94 html_cutoff_text = None
95
96 def __init__(self, **kwargs):
97 self.queryset = kwargs.pop('queryset', self.queryset)
98
99 cutoff_from_settings = api_settings.HTML_SELECT_CUTOFF
100 if cutoff_from_settings is not None:
101 cutoff_from_settings = int(cutoff_from_settings)
102 self.html_cutoff = kwargs.pop('html_cutoff', cutoff_from_settings)
103
104 self.html_cutoff_text = kwargs.pop(
105 'html_cutoff_text',
106 self.html_cutoff_text or _(api_settings.HTML_SELECT_CUTOFF_TEXT)
107 )
108 if not method_overridden('get_queryset', RelatedField, self):
109 assert self.queryset is not None or kwargs.get('read_only'), (
110 'Relational field must provide a `queryset` argument, '
111 'override `get_queryset`, or set read_only=`True`.'
112 )
113 assert not (self.queryset is not None and kwargs.get('read_only')), (
114 'Relational fields should not provide a `queryset` argument, '
115 'when setting read_only=`True`.'
116 )
117 kwargs.pop('many', None)
118 kwargs.pop('allow_empty', None)
119 super().__init__(**kwargs)
120
121 def __new__(cls, *args, **kwargs):
122 # We override this method in order to automagically create
123 # `ManyRelatedField` classes instead when `many=True` is set.
124 if kwargs.pop('many', False):
125 return cls.many_init(*args, **kwargs)
126 return super().__new__(cls, *args, **kwargs)
127
128 @classmethod
129 def many_init(cls, *args, **kwargs):
130 """
131 This method handles creating a parent `ManyRelatedField` instance
132 when the `many=True` keyword argument is passed.
133
134 Typically you won't need to override this method.
135
136 Note that we're over-cautious in passing most arguments to both parent
137 and child classes in order to try to cover the general case. If you're
138 overriding this method you'll probably want something much simpler, eg:
139
140 @classmethod
141 def many_init(cls, *args, **kwargs):
142 kwargs['child'] = cls()
143 return CustomManyRelatedField(*args, **kwargs)
144 """
145 list_kwargs = {'child_relation': cls(*args, **kwargs)}
146 for key in kwargs:
147 if key in MANY_RELATION_KWARGS:
148 list_kwargs[key] = kwargs[key]
149 return ManyRelatedField(**list_kwargs)
150
151 def run_validation(self, data=empty):
152 # We force empty strings to None values for relational fields.
153 if data == '':
154 data = None
155 return super().run_validation(data)
156
157 def get_queryset(self):
158 queryset = self.queryset
159 if isinstance(queryset, (QuerySet, Manager)):
160 # Ensure queryset is re-evaluated whenever used.
161 # Note that actually a `Manager` class may also be used as the
162 # queryset argument. This occurs on ModelSerializer fields,
163 # as it allows us to generate a more expressive 'repr' output
164 # for the field.
165 # Eg: 'MyRelationship(queryset=ExampleModel.objects.all())'
166 queryset = queryset.all()
167 return queryset
168
169 def use_pk_only_optimization(self):
170 return False
171
172 def get_attribute(self, instance):
173 if self.use_pk_only_optimization() and self.source_attrs:
174 # Optimized case, return a mock object only containing the pk attribute.
175 with contextlib.suppress(AttributeError):
176 attribute_instance = get_attribute(instance, self.source_attrs[:-1])
177 value = attribute_instance.serializable_value(self.source_attrs[-1])
178 if is_simple_callable(value):
179 # Handle edge case where the relationship `source` argument
180 # points to a `get_relationship()` method on the model.
181 value = value()
182
183 # Handle edge case where relationship `source` argument points
184 # to an instance instead of a pk (e.g., a `@property`).
185 value = getattr(value, 'pk', value)
186
187 return PKOnlyObject(pk=value)
188 # Standard case, return the object instance.
189 return super().get_attribute(instance)
190
191 def get_choices(self, cutoff=None):
192 queryset = self.get_queryset()
193 if queryset is None:
194 # Ensure that field.choices returns something sensible
195 # even when accessed with a read-only field.
196 return {}
197
198 if cutoff is not None:
199 queryset = queryset[:cutoff]
200
201 return {
202 self.to_representation(item): self.display_value(item) for item in queryset
203 }
204
205 @property
206 def choices(self):
207 return self.get_choices()
208
209 @property
210 def grouped_choices(self):
211 return self.choices
212
213 def iter_options(self):
214 return iter_options(
215 self.get_choices(cutoff=self.html_cutoff),
216 cutoff=self.html_cutoff,
217 cutoff_text=self.html_cutoff_text
218 )
219
220 def display_value(self, instance):
221 return str(instance)
222
223
224 class StringRelatedField(RelatedField):
225 """
226 A read only field that represents its targets using their
227 plain string representation.
228 """
229
230 def __init__(self, **kwargs):
231 kwargs['read_only'] = True
232 super().__init__(**kwargs)
233
234 def to_representation(self, value):
235 return str(value)
236
237
238 class PrimaryKeyRelatedField(RelatedField):
239 default_error_messages = {
240 'required': _('This field is required.'),
241 'does_not_exist': _('Invalid pk "{pk_value}" - object does not exist.'),
242 'incorrect_type': _('Incorrect type. Expected pk value, received {data_type}.'),
243 }
244
245 def __init__(self, **kwargs):
246 self.pk_field = kwargs.pop('pk_field', None)
247 super().__init__(**kwargs)
248
249 def use_pk_only_optimization(self):
250 return True
251
252 def to_internal_value(self, data):
253 if self.pk_field is not None:
254 data = self.pk_field.to_internal_value(data)
255 queryset = self.get_queryset()
256 try:
257 if isinstance(data, bool):
258 raise TypeError
259 return queryset.get(pk=data)
260 except ObjectDoesNotExist:
261 self.fail('does_not_exist', pk_value=data)
262 except (TypeError, ValueError):
263 self.fail('incorrect_type', data_type=type(data).__name__)
264
265 def to_representation(self, value):
266 if self.pk_field is not None:
267 return self.pk_field.to_representation(value.pk)
268 return value.pk
269
270
271 class HyperlinkedRelatedField(RelatedField):
272 lookup_field = 'pk'
273 view_name = None
274
275 default_error_messages = {
276 'required': _('This field is required.'),
277 'no_match': _('Invalid hyperlink - No URL match.'),
278 'incorrect_match': _('Invalid hyperlink - Incorrect URL match.'),
279 'does_not_exist': _('Invalid hyperlink - Object does not exist.'),
280 'incorrect_type': _('Incorrect type. Expected URL string, received {data_type}.'),
281 }
282
283 def __init__(self, view_name=None, **kwargs):
284 if view_name is not None:
285 self.view_name = view_name
286 assert self.view_name is not None, 'The `view_name` argument is required.'
287 self.lookup_field = kwargs.pop('lookup_field', self.lookup_field)
288 self.lookup_url_kwarg = kwargs.pop('lookup_url_kwarg', self.lookup_field)
289 self.format = kwargs.pop('format', None)
290
291 # We include this simply for dependency injection in tests.
292 # We can't add it as a class attributes or it would expect an
293 # implicit `self` argument to be passed.
294 self.reverse = reverse
295
296 super().__init__(**kwargs)
297
298 def use_pk_only_optimization(self):
299 return self.lookup_field == 'pk'
300
301 def get_object(self, view_name, view_args, view_kwargs):
302 """
303 Return the object corresponding to a matched URL.
304
305 Takes the matched URL conf arguments, and should return an
306 object instance, or raise an `ObjectDoesNotExist` exception.
307 """
308 lookup_value = view_kwargs[self.lookup_url_kwarg]
309 lookup_kwargs = {self.lookup_field: lookup_value}
310 queryset = self.get_queryset()
311
312 try:
313 return queryset.get(**lookup_kwargs)
314 except ValueError:
315 exc = ObjectValueError(str(sys.exc_info()[1]))
316 raise exc.with_traceback(sys.exc_info()[2])
317 except TypeError:
318 exc = ObjectTypeError(str(sys.exc_info()[1]))
319 raise exc.with_traceback(sys.exc_info()[2])
320
321 def get_url(self, obj, view_name, request, format):
322 """
323 Given an object, return the URL that hyperlinks to the object.
324
325 May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
326 attributes are not configured to correctly match the URL conf.
327 """
328 # Unsaved objects will not yet have a valid URL.
329 if hasattr(obj, 'pk') and obj.pk in (None, ''):
330 return None
331
332 lookup_value = getattr(obj, self.lookup_field)
333 kwargs = {self.lookup_url_kwarg: lookup_value}
334 return self.reverse(view_name, kwargs=kwargs, request=request, format=format)
335
336 def to_internal_value(self, data):
337 request = self.context.get('request')
338 try:
339 http_prefix = data.startswith(('http:', 'https:'))
340 except AttributeError:
341 self.fail('incorrect_type', data_type=type(data).__name__)
342
343 if http_prefix:
344 # If needed convert absolute URLs to relative path
345 data = parse.urlparse(data).path
346 prefix = get_script_prefix()
347 if data.startswith(prefix):
348 data = '/' + data[len(prefix):]
349
350 data = uri_to_iri(parse.unquote(data))
351
352 try:
353 match = resolve(data)
354 except Resolver404:
355 self.fail('no_match')
356
357 try:
358 expected_viewname = request.versioning_scheme.get_versioned_viewname(
359 self.view_name, request
360 )
361 except AttributeError:
362 expected_viewname = self.view_name
363
364 if match.view_name != expected_viewname:
365 self.fail('incorrect_match')
366
367 try:
368 return self.get_object(match.view_name, match.args, match.kwargs)
369 except (ObjectDoesNotExist, ObjectValueError, ObjectTypeError):
370 self.fail('does_not_exist')
371
372 def to_representation(self, value):
373 assert 'request' in self.context, (
374 "`%s` requires the request in the serializer"
375 " context. Add `context={'request': request}` when instantiating "
376 "the serializer." % self.__class__.__name__
377 )
378
379 request = self.context['request']
380 format = self.context.get('format')
381
382 # By default use whatever format is given for the current context
383 # unless the target is a different type to the source.
384 #
385 # Eg. Consider a HyperlinkedIdentityField pointing from a json
386 # representation to an html property of that representation...
387 #
388 # '/snippets/1/' should link to '/snippets/1/highlight/'
389 # ...but...
390 # '/snippets/1/.json' should link to '/snippets/1/highlight/.html'
391 if format and self.format and self.format != format:
392 format = self.format
393
394 # Return the hyperlink, or error if incorrectly configured.
395 try:
396 url = self.get_url(value, self.view_name, request, format)
397 except NoReverseMatch:
398 msg = (
399 'Could not resolve URL for hyperlinked relationship using '
400 'view name "%s". You may have failed to include the related '
401 'model in your API, or incorrectly configured the '
402 '`lookup_field` attribute on this field.'
403 )
404 if value in ('', None):
405 value_string = {'': 'the empty string', None: 'None'}[value]
406 msg += (
407 " WARNING: The value of the field on the model instance "
408 "was %s, which may be why it didn't match any "
409 "entries in your URL conf." % value_string
410 )
411 raise ImproperlyConfigured(msg % self.view_name)
412
413 if url is None:
414 return None
415
416 return Hyperlink(url, value)
417
418
419 class HyperlinkedIdentityField(HyperlinkedRelatedField):
420 """
421 A read-only field that represents the identity URL for an object, itself.
422
423 This is in contrast to `HyperlinkedRelatedField` which represents the
424 URL of relationships to other objects.
425 """
426
427 def __init__(self, view_name=None, **kwargs):
428 assert view_name is not None, 'The `view_name` argument is required.'
429 kwargs['read_only'] = True
430 kwargs['source'] = '*'
431 super().__init__(view_name, **kwargs)
432
433 def use_pk_only_optimization(self):
434 # We have the complete object instance already. We don't need
435 # to run the 'only get the pk for this relationship' code.
436 return False
437
438
439 class SlugRelatedField(RelatedField):
440 """
441 A read-write field that represents the target of the relationship
442 by a unique 'slug' attribute.
443 """
444 default_error_messages = {
445 'does_not_exist': _('Object with {slug_name}={value} does not exist.'),
446 'invalid': _('Invalid value.'),
447 }
448
449 def __init__(self, slug_field=None, **kwargs):
450 assert slug_field is not None, 'The `slug_field` argument is required.'
451 self.slug_field = slug_field
452 super().__init__(**kwargs)
453
454 def to_internal_value(self, data):
455 queryset = self.get_queryset()
456 try:
457 return queryset.get(**{self.slug_field: data})
458 except ObjectDoesNotExist:
459 self.fail('does_not_exist', slug_name=self.slug_field, value=smart_str(data))
460 except (TypeError, ValueError):
461 self.fail('invalid')
462
463 def to_representation(self, obj):
464 slug = self.slug_field
465 if "__" in slug:
466 # handling nested relationship if defined
467 slug = slug.replace('__', '.')
468 return attrgetter(slug)(obj)
469
470
471 class ManyRelatedField(Field):
472 """
473 Relationships with `many=True` transparently get coerced into instead being
474 a ManyRelatedField with a child relationship.
475
476 The `ManyRelatedField` class is responsible for handling iterating through
477 the values and passing each one to the child relationship.
478
479 This class is treated as private API.
480 You shouldn't generally need to be using this class directly yourself,
481 and should instead simply set 'many=True' on the relationship.
482 """
483 initial = []
484 default_empty_html = []
485 default_error_messages = {
486 'not_a_list': _('Expected a list of items but got type "{input_type}".'),
487 'empty': _('This list may not be empty.')
488 }
489 html_cutoff = None
490 html_cutoff_text = None
491
492 def __init__(self, child_relation=None, *args, **kwargs):
493 self.child_relation = child_relation
494 self.allow_empty = kwargs.pop('allow_empty', True)
495
496 cutoff_from_settings = api_settings.HTML_SELECT_CUTOFF
497 if cutoff_from_settings is not None:
498 cutoff_from_settings = int(cutoff_from_settings)
499 self.html_cutoff = kwargs.pop('html_cutoff', cutoff_from_settings)
500
501 self.html_cutoff_text = kwargs.pop(
502 'html_cutoff_text',
503 self.html_cutoff_text or _(api_settings.HTML_SELECT_CUTOFF_TEXT)
504 )
505 assert child_relation is not None, '`child_relation` is a required argument.'
506 super().__init__(*args, **kwargs)
507 self.child_relation.bind(field_name='', parent=self)
508
509 def get_value(self, dictionary):
510 # We override the default field access in order to support
511 # lists in HTML forms.
512 if html.is_html_input(dictionary):
513 # Don't return [] if the update is partial
514 if self.field_name not in dictionary:
515 if getattr(self.root, 'partial', False):
516 return empty
517 return dictionary.getlist(self.field_name)
518
519 return dictionary.get(self.field_name, empty)
520
521 def to_internal_value(self, data):
522 if isinstance(data, str) or not hasattr(data, '__iter__'):
523 self.fail('not_a_list', input_type=type(data).__name__)
524 if not self.allow_empty and len(data) == 0:
525 self.fail('empty')
526
527 return [
528 self.child_relation.to_internal_value(item)
529 for item in data
530 ]
531
532 def get_attribute(self, instance):
533 # Can't have any relationships if not created
534 if hasattr(instance, 'pk') and instance.pk is None:
535 return []
536
537 try:
538 relationship = get_attribute(instance, self.source_attrs)
539 except (KeyError, AttributeError) as exc:
540 if self.default is not empty:
541 return self.get_default()
542 if self.allow_null:
543 return None
544 if not self.required:
545 raise SkipField()
546 msg = (
547 'Got {exc_type} when attempting to get a value for field '
548 '`{field}` on serializer `{serializer}`.\nThe serializer '
549 'field might be named incorrectly and not match '
550 'any attribute or key on the `{instance}` instance.\n'
551 'Original exception text was: {exc}.'.format(
552 exc_type=type(exc).__name__,
553 field=self.field_name,
554 serializer=self.parent.__class__.__name__,
555 instance=instance.__class__.__name__,
556 exc=exc
557 )
558 )
559 raise type(exc)(msg)
560
561 return relationship.all() if hasattr(relationship, 'all') else relationship
562
563 def to_representation(self, iterable):
564 return [
565 self.child_relation.to_representation(value)
566 for value in iterable
567 ]
568
569 def get_choices(self, cutoff=None):
570 return self.child_relation.get_choices(cutoff)
571
572 @property
573 def choices(self):
574 return self.get_choices()
575
576 @property
577 def grouped_choices(self):
578 return self.choices
579
580 def iter_options(self):
581 return iter_options(
582 self.get_choices(cutoff=self.html_cutoff),
583 cutoff=self.html_cutoff,
584 cutoff_text=self.html_cutoff_text
585 )