|
1 | | -# Patchwork - automated patch tracking system |
2 | | -# Copyright (C) 2020, Stephen Finucane <stephen@that.guru> |
3 | | -# |
4 | | -# SPDX-License-Identifier: GPL-2.0-or-later |
5 | | - |
6 | | -from rest_framework.fields import empty |
7 | | -from rest_framework.fields import get_attribute |
8 | | -from rest_framework.fields import SkipField |
9 | | -from rest_framework.relations import ManyRelatedField |
10 | | - |
11 | | - |
12 | | -# monkey patch django-rest-framework to work around issue #7550 [1] until #7574 |
13 | | -# [2] or some other variant lands |
14 | | -# |
15 | | -# [1] https://github.com/encode/django-rest-framework/issues/7550 |
16 | | -# [2] https://github.com/encode/django-rest-framework/pull/7574 |
17 | | - |
18 | | - |
19 | | -def _get_attribute(self, instance): |
20 | | - # Can't have any relationships if not created |
21 | | - if hasattr(instance, 'pk') and instance.pk is None: |
22 | | - return [] |
23 | | - |
24 | | - try: |
25 | | - relationship = get_attribute(instance, self.source_attrs) |
26 | | - except (KeyError, AttributeError) as exc: |
27 | | - if self.default is not empty: |
28 | | - return self.get_default() |
29 | | - if self.allow_null: |
30 | | - return None |
31 | | - if not self.required: |
32 | | - raise SkipField() |
33 | | - msg = ( |
34 | | - 'Got {exc_type} when attempting to get a value for field ' |
35 | | - '`{field}` on serializer `{serializer}`.\nThe serializer ' |
36 | | - 'field might be named incorrectly and not match ' |
37 | | - 'any attribute or key on the `{instance}` instance.\n' |
38 | | - 'Original exception text was: {exc}.'.format( |
39 | | - exc_type=type(exc).__name__, |
40 | | - field=self.field_name, |
41 | | - serializer=self.parent.__class__.__name__, |
42 | | - instance=instance.__class__.__name__, |
43 | | - exc=exc, |
44 | | - ) |
45 | | - ) |
46 | | - raise type(exc)(msg) |
47 | | - |
48 | | - return relationship.all() if hasattr(relationship, 'all') else relationship |
49 | | - |
50 | | - |
51 | | -ManyRelatedField.get_attribute = _get_attribute |
0 commit comments