You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

relations.py 19KB

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