-
Notifications
You must be signed in to change notification settings - Fork 267
/
Copy pathfields.py
268 lines (196 loc) · 7.01 KB
/
fields.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
from types import MethodType
import django
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.db.models.fields.files import FieldFile
if django.VERSION < (4, 0):
from django.utils.encoding import force_text as force_str
else:
from django.utils.encoding import force_str
from django.utils.functional import Promise
from elasticsearch_dsl.field import (
Boolean,
Byte,
Completion,
Date,
Double,
Field,
Float,
GeoPoint,
GeoShape,
Integer,
Ip,
Long,
Nested,
Object,
ScaledFloat,
Short,
Keyword,
Text,
SearchAsYouType,
)
from .exceptions import VariableLookupError
class DEDField(Field):
def __init__(self, attr=None, **kwargs):
super(DEDField, self).__init__(**kwargs)
self._path = attr.split('.') if attr else []
def __setattr__(self, key, value):
if key == 'get_value_from_instance':
self.__dict__[key] = value
else:
super(DEDField, self).__setattr__(key, value)
def get_value_from_instance(self, instance, field_value_to_ignore=None):
"""
Given an model instance to index with ES, return the value that
should be put into ES for this field.
"""
if not instance:
return None
for attr in self._path:
try:
instance = instance[attr]
except (
TypeError, AttributeError,
KeyError, ValueError, IndexError
):
try:
instance = getattr(instance, attr)
except ObjectDoesNotExist:
return None
except (TypeError, AttributeError):
try:
instance = instance[int(attr)]
except (
IndexError, ValueError,
KeyError, TypeError
):
if self._required:
raise VariableLookupError(
"Failed lookup for key [{}] in "
"{!r}".format(attr, instance)
)
return None
if isinstance(instance, models.manager.Manager):
instance = instance.all()
elif callable(instance):
instance = instance()
elif instance is None:
return None
if instance == field_value_to_ignore:
return None
# convert lazy object like lazy translations to string
if isinstance(instance, Promise):
return force_str(instance)
return instance
class ObjectField(DEDField, Object):
def _get_inner_field_data(self, obj, field_value_to_ignore=None):
data = {}
if hasattr(self, 'properties'):
for name, field in self.properties.to_dict().items():
if not isinstance(field, DEDField):
continue
if field._path == []:
field._path = [name]
data[name] = field.get_value_from_instance(
obj, field_value_to_ignore
)
else:
doc_instance = self._doc_class()
for name, field in self._doc_class._doc_type.mapping.properties._params.get(
'properties', {}).items(): # noqa
if not isinstance(field, DEDField):
continue
if field._path == []:
field._path = [name]
# This allows for retrieving data from an InnerDoc with prepare_field_name functions.
prep_func = getattr(doc_instance, 'prepare_%s' % name, None)
if prep_func:
data[name] = prep_func(obj)
else:
data[name] = field.get_value_from_instance(
obj, field_value_to_ignore
)
# This allows for ObjectFields to be indexed from dicts with
# dynamic keys (i.e. keys/fields not defined in 'properties')
if not data and obj and isinstance(obj, dict):
data = obj
return data
def get_value_from_instance(self, instance, field_value_to_ignore=None):
objs = super(ObjectField, self).get_value_from_instance(
instance, field_value_to_ignore
)
if objs is None:
return {}
try:
is_iterable = bool(iter(objs))
except TypeError:
is_iterable = False
# While dicts are iterable, they need to be excluded here so
# their full data is indexed
if is_iterable and not isinstance(objs, dict):
return [
self._get_inner_field_data(obj, field_value_to_ignore)
for obj in objs if obj != field_value_to_ignore
]
return self._get_inner_field_data(objs, field_value_to_ignore)
def ListField(field):
"""
This wraps a field so that when get_value_from_instance
is called, the field's values are iterated over
"""
original_get_value_from_instance = field.get_value_from_instance
def get_value_from_instance(self, instance, field_value_to_ignore=None):
if not original_get_value_from_instance(instance):
return []
return [value for value in original_get_value_from_instance(instance)]
field.get_value_from_instance = MethodType(get_value_from_instance, field)
return field
class BooleanField(DEDField, Boolean):
pass
class ByteField(DEDField, Byte):
pass
class CompletionField(DEDField, Completion):
pass
class DateField(DEDField, Date):
pass
class DoubleField(DEDField, Double):
pass
class FloatField(DEDField, Float):
pass
class ScaledFloatField(DEDField, ScaledFloat):
pass
class GeoPointField(DEDField, GeoPoint):
pass
class GeoShapeField(DEDField, GeoShape):
pass
class IntegerField(DEDField, Integer):
pass
class IpField(DEDField, Ip):
pass
class LongField(DEDField, Long):
pass
class NestedField(Nested, ObjectField):
pass
class ShortField(DEDField, Short):
pass
class KeywordField(DEDField, Keyword):
pass
class TextField(DEDField, Text):
pass
class SearchAsYouTypeField(DEDField, SearchAsYouType):
pass
class FileFieldMixin(object):
def get_value_from_instance(self, instance, field_value_to_ignore=None):
_file = super(FileFieldMixin, self).get_value_from_instance(
instance, field_value_to_ignore)
if isinstance(_file, FieldFile):
return _file.url if _file else ''
return _file if _file else ''
class FileField(FileFieldMixin, DEDField, Text):
pass
class TimeField(KeywordField):
def get_value_from_instance(self, instance, field_value_to_ignore=None):
time = super(TimeField, self).get_value_from_instance(instance,
field_value_to_ignore)
if time:
return time.isoformat()