forked from django-json-api/django-rest-framework-json-api
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrelations.py
268 lines (216 loc) · 10.8 KB
/
relations.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
importcollections
importjson
fromrest_framework.fieldsimportMISSING_ERROR_MESSAGE, SerializerMethodField
fromrest_framework.relationsimport*
fromdjango.utils.translationimportugettext_lazyas_
fromdjango.db.models.queryimportQuerySet
fromrest_framework_json_api.exceptionsimportConflict
fromrest_framework_json_api.utilsimportPOLYMORPHIC_ANCESTORS, Hyperlink, \
get_resource_type_from_queryset, get_resource_type_from_instance, \
get_included_serializers, get_resource_type_from_serializer
LINKS_PARAMS= ['self_link_view_name', 'related_link_view_name', 'related_link_lookup_field', 'related_link_url_kwarg']
classResourceRelatedField(PrimaryKeyRelatedField):
_skip_polymorphic_optimization=True
self_link_view_name=None
related_link_view_name=None
related_link_lookup_field='pk'
default_error_messages= {
'required': _('This field is required.'),
'does_not_exist': _('Invalid pk "{pk_value}" - object does not exist.'),
'incorrect_type': _('Incorrect type. Expected resource identifier object, received {data_type}.'),
'incorrect_relation_type': _('Incorrect relation type. Expected {relation_type}, received {received_type}.'),
'missing_type': _('Invalid resource identifier object: missing \'type\' attribute'),
'missing_id': _('Invalid resource identifier object: missing \'id\' attribute'),
'no_match': _('Invalid hyperlink - No URL match.'),
}
def__init__(self, self_link_view_name=None, related_link_view_name=None, **kwargs):
ifself_link_view_nameisnotNone:
self.self_link_view_name=self_link_view_name
ifrelated_link_view_nameisnotNone:
self.related_link_view_name=related_link_view_name
self.related_link_lookup_field=kwargs.pop('related_link_lookup_field', self.related_link_lookup_field)
self.related_link_url_kwarg=kwargs.pop('related_link_url_kwarg', self.related_link_lookup_field)
# check for a model class that was passed in for the relation type
model=kwargs.pop('model', None)
ifmodel:
self.model=model
# We include this simply for dependency injection in tests.
# We can't add it as a class attributes or it would expect an
# implicit `self` argument to be passed.
self.reverse=reverse
super(ResourceRelatedField, self).__init__(**kwargs)
# Determine if relation is polymorphic
self.is_polymorphic=False
model=modelorgetattr(self.get_queryset(), 'model', None)
ifmodelandissubclass(model, POLYMORPHIC_ANCESTORS):
self.is_polymorphic=True
defuse_pk_only_optimization(self):
# We need the real object to determine its type...
returnFalse
defconflict(self, key, **kwargs):
"""
A helper method that simply raises a validation error.
"""
try:
msg=self.error_messages[key]
exceptKeyError:
class_name=self.__class__.__name__
msg=MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key)
raiseAssertionError(msg)
message_string=msg.format(**kwargs)
raiseConflict(message_string)
defget_url(self, name, view_name, kwargs, request):
"""
Given a name, view name and kwargs, return the URL that hyperlinks to the object.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf.
"""
# Return None if the view name is not supplied
ifnotview_name:
returnNone
# Return the hyperlink, or error if incorrectly configured.
try:
url=self.reverse(view_name, kwargs=kwargs, request=request)
exceptNoReverseMatch:
msg= (
'Could not resolve URL for hyperlinked relationship using '
'view name "%s".'
)
raiseImproperlyConfigured(msg%view_name)
ifurlisNone:
returnNone
returnHyperlink(url, name)
defget_links(self, obj=None, lookup_field='pk'):
request=self.context.get('request', None)
view=self.context.get('view', None)
return_data=OrderedDict()
kwargs= {lookup_field: getattr(obj, lookup_field) ifobjelseview.kwargs[lookup_field]}
self_kwargs=kwargs.copy()
self_kwargs.update({'related_field': self.field_nameifself.field_nameelseself.parent.field_name})
self_link=self.get_url('self', self.self_link_view_name, self_kwargs, request)
related_kwargs= {self.related_link_url_kwarg: kwargs[self.related_link_lookup_field]}
related_link=self.get_url('related', self.related_link_view_name, related_kwargs, request)
ifself_link:
return_data.update({'self': self_link})
ifrelated_link:
return_data.update({'related': related_link})
returnreturn_data
defto_internal_value(self, data):
ifisinstance(data, six.text_type):
try:
data=json.loads(data)
exceptValueError:
# show a useful error if they send a `pk` instead of resource object
self.fail('incorrect_type', data_type=type(data).__name__)
ifnotisinstance(data, dict):
self.fail('incorrect_type', data_type=type(data).__name__)
expected_relation_type=get_resource_type_from_queryset(self.queryset)
if'type'notindata:
self.fail('missing_type')
if'id'notindata:
self.fail('missing_id')
ifdata['type'] !=expected_relation_type:
self.conflict('incorrect_relation_type', relation_type=expected_relation_type,
received_type=data['type'])
returnsuper(ResourceRelatedField, self).to_internal_value(data['id'])
defto_representation(self, value):
ifgetattr(self, 'pk_field', None) isnotNone:
pk=self.pk_field.to_representation(value.pk)
else:
pk=value.pk
# check to see if this resource has a different resource_name when
# included and use that name
resource_type=None
root=getattr(self.parent, 'parent', self.parent)
field_name=self.field_nameifself.field_nameelseself.parent.field_name
ifgetattr(root, 'included_serializers', None) isnotNoneand \
self._skip_polymorphic_optimization:
includes=get_included_serializers(root)
iffield_nameinincludes.keys():
resource_type=get_resource_type_from_serializer(includes[field_name])
resource_type=resource_typeifresource_typeelseget_resource_type_from_instance(value)
returnOrderedDict([('type', resource_type), ('id', str(pk))])
defget_choices(self, cutoff=None):
queryset=self.get_queryset()
ifquerysetisNone:
# Ensure that field.choices returns something sensible
# even when accessed with a read-only field.
return {}
ifcutoffisnotNone:
queryset=queryset[:cutoff]
returnOrderedDict([
(
json.dumps(self.to_representation(item)),
self.display_value(item)
)
foriteminqueryset
])
classPolymorphicResourceRelatedField(ResourceRelatedField):
_skip_polymorphic_optimization=False
default_error_messages=dict(ResourceRelatedField.default_error_messages, **{
'incorrect_relation_type': _('Incorrect relation type. Expected one of [{relation_type}], '
'received {received_type}.'),
})
def__init__(self, polymorphic_serializer, *args, **kwargs):
self.polymorphic_serializer=polymorphic_serializer
super(PolymorphicResourceRelatedField, self).__init__(*args, **kwargs)
defto_internal_value(self, data):
ifisinstance(data, six.text_type):
try:
data=json.loads(data)
exceptValueError:
# show a useful error if they send a `pk` instead of resource object
self.fail('incorrect_type', data_type=type(data).__name__)
ifnotisinstance(data, dict):
self.fail('incorrect_type', data_type=type(data).__name__)
if'type'notindata:
self.fail('missing_type')
if'id'notindata:
self.fail('missing_id')
expected_relation_types=self.polymorphic_serializer.get_polymorphic_types()
ifdata['type'] notinexpected_relation_types:
self.conflict('incorrect_relation_type', relation_type=", ".join(
expected_relation_types), received_type=data['type'])
returnsuper(ResourceRelatedField, self).to_internal_value(data['id'])
classSerializerMethodResourceRelatedField(ResourceRelatedField):
"""
Allows us to use serializer method RelatedFields
with return querysets
"""
def__new__(cls, *args, **kwargs):
"""
We override this because getting serializer methods
fails at the base class when many=True
"""
ifkwargs.pop('many', False):
returncls.many_init(*args, **kwargs)
returnsuper(ResourceRelatedField, cls).__new__(cls, *args, **kwargs)
def__init__(self, child_relation=None, *args, **kwargs):
# DRF 3.1 doesn't expect the `many` kwarg
kwargs.pop('many', None)
model=kwargs.pop('model', None)
ifchild_relationisnotNone:
self.child_relation=child_relation
ifmodel:
self.model=model
super(SerializerMethodResourceRelatedField, self).__init__(*args, **kwargs)
@classmethod
defmany_init(cls, *args, **kwargs):
list_kwargs= {k: kwargs.pop(k) forkinLINKS_PARAMSifkinkwargs}
list_kwargs['child_relation'] =cls(*args, **kwargs)
forkeyinkwargs.keys():
ifkeyin ('model',) +MANY_RELATION_KWARGS:
list_kwargs[key] =kwargs[key]
returncls(**list_kwargs)
defget_attribute(self, instance):
# check for a source fn defined on the serializer instead of the model
ifself.sourceandhasattr(self.parent, self.source):
serializer_method=getattr(self.parent, self.source)
ifhasattr(serializer_method, '__call__'):
returnserializer_method(instance)
returnsuper(SerializerMethodResourceRelatedField, self).get_attribute(instance)
defto_representation(self, value):
ifisinstance(value, collections.Iterable):
base=super(SerializerMethodResourceRelatedField, self)
return [base.to_representation(x) forxinvalue]
returnsuper(SerializerMethodResourceRelatedField, self).to_representation(value)