Debian Codegraph @

drf_haystack/serializers.py

raw
1 # -*- coding: utf-8 -*-
2
3 from __future__ import absolute_import, unicode_literals
4
5 import copy
6 import six
7 import warnings
8 from itertools import chain
9 from datetime import datetime
10
11 try:
12 from collections import OrderedDict
13 except ImportError:
14 from django.utils.datastructures import SortedDict as OrderedDict
15
16 from django.core.exceptions import ImproperlyConfigured, FieldDoesNotExist
17
18 from haystack import fields as haystack_fields
19 from haystack.query import EmptySearchQuerySet
20 from haystack.utils.highlighting import Highlighter
21
22 from rest_framework import serializers
23 from rest_framework.fields import empty
24 from rest_framework.utils.field_mapping import ClassLookupDict, get_field_kwargs
25
26 from drf_haystack.fields import (
27 HaystackBooleanField, HaystackCharField, HaystackDateField, HaystackDateTimeField,
28 HaystackDecimalField, HaystackFloatField, HaystackIntegerField, HaystackMultiValueField,
29 FacetDictField, FacetListField
30 )
31
32
33 class Meta(type):
34 """
35 Template for the HaystackSerializerMeta.Meta class.
36 """
37
38 fields = tuple()
39 exclude = tuple()
40 search_fields = tuple()
41 index_classes = tuple()
42 serializers = tuple()
43 ignore_fields = tuple()
44 field_aliases = {}
45 field_options = {}
46 index_aliases = {}
47
48 def __new__(mcs, name, bases, attrs):
49 cls = super(Meta, mcs).__new__(mcs, str(name), bases, attrs)
50
51 if cls.fields and cls.exclude:
52 raise ImproperlyConfigured("%s cannot define both 'fields' and 'exclude'." % name)
53
54 return cls
55
56 def __setattr__(cls, key, value):
57 raise AttributeError("Meta class is immutable.")
58
59 def __delattr__(cls, key, value):
60 raise AttributeError("Meta class is immutable.")
61
62
63 class HaystackSerializerMeta(serializers.SerializerMetaclass):
64
65 """
66 Metaclass for the HaystackSerializer that ensures that all declared subclasses implemented a Meta.
67 """
68
69 def __new__(mcs, name, bases, attrs):
70 attrs.setdefault("_abstract", False)
71
72 cls = super(HaystackSerializerMeta, mcs).__new__(mcs, str(name), bases, attrs)
73
74 if getattr(cls, "Meta", None):
75 cls.Meta = Meta("Meta", (Meta,), dict(cls.Meta.__dict__))
76
77 elif not cls._abstract:
78 raise ImproperlyConfigured("%s must implement a Meta class or have the property _abstract" % name)
79
80 return cls
81
82
83 class HaystackSerializer(six.with_metaclass(HaystackSerializerMeta, serializers.Serializer)):
84 """
85 A `HaystackSerializer` which populates fields based on
86 which models that are available in the SearchQueryset.
87 """
88
89 _abstract = True
90
91 _field_mapping = ClassLookupDict({
92 haystack_fields.BooleanField: HaystackBooleanField,
93 haystack_fields.CharField: HaystackCharField,
94 haystack_fields.DateField: HaystackDateField,
95 haystack_fields.DateTimeField: HaystackDateTimeField,
96 haystack_fields.DecimalField: HaystackDecimalField,
97 haystack_fields.EdgeNgramField: HaystackCharField,
98 haystack_fields.FacetBooleanField: HaystackBooleanField,
99 haystack_fields.FacetCharField: HaystackCharField,
100 haystack_fields.FacetDateField: HaystackDateField,
101 haystack_fields.FacetDateTimeField: HaystackDateTimeField,
102 haystack_fields.FacetDecimalField: HaystackDecimalField,
103 haystack_fields.FacetFloatField: HaystackFloatField,
104 haystack_fields.FacetIntegerField: HaystackIntegerField,
105 haystack_fields.FacetMultiValueField: HaystackMultiValueField,
106 haystack_fields.FloatField: HaystackFloatField,
107 haystack_fields.IntegerField: HaystackIntegerField,
108 haystack_fields.LocationField: HaystackCharField,
109 haystack_fields.MultiValueField: HaystackMultiValueField,
110 haystack_fields.NgramField: HaystackCharField,
111 })
112
113 def __init__(self, instance=None, data=empty, **kwargs):
114 super(HaystackSerializer, self).__init__(instance, data, **kwargs)
115
116 if not self.Meta.index_classes and not self.Meta.serializers:
117 raise ImproperlyConfigured("You must set either the 'index_classes' or 'serializers' "
118 "attribute on the serializer Meta class.")
119
120 if not self.instance:
121 self.instance = EmptySearchQuerySet()
122
123 @staticmethod
124 def _get_default_field_kwargs(model, field):
125 """
126 Get the required attributes from the model field in order
127 to instantiate a REST Framework serializer field.
128 """
129 kwargs = {}
130 try:
131 field_name = field.model_attr or field.index_fieldname
132 model_field = model._meta.get_field(field_name)
133 kwargs.update(get_field_kwargs(field_name, model_field))
134
135 # Remove stuff we don't care about!
136 delete_attrs = [
137 "allow_blank",
138 "choices",
139 "model_field",
140 "allow_unicode",
141 ]
142 for attr in delete_attrs:
143 if attr in kwargs:
144 del kwargs[attr]
145 except FieldDoesNotExist:
146 pass
147
148 return kwargs
149
150 def _get_index_field(self, field_name):
151 """
152 Returns the correct index field.
153 """
154 return field_name
155
156 def _get_index_class_name(self, index_cls):
157 """
158 Converts in index model class to a name suitable for use as a field name prefix. A user
159 may optionally specify custom aliases via an 'index_aliases' attribute on the Meta class
160 """
161 cls_name = index_cls.__name__
162 aliases = self.Meta.index_aliases
163 return aliases.get(cls_name, cls_name.split('.')[-1])
164
165 def get_fields(self):
166 """
167 Get the required fields for serializing the result.
168 """
169
170 fields = self.Meta.fields
171 exclude = self.Meta.exclude
172 ignore_fields = self.Meta.ignore_fields
173 indices = self.Meta.index_classes
174
175 declared_fields = copy.deepcopy(self._declared_fields)
176 prefix_field_names = len(indices) > 1
177 field_mapping = OrderedDict()
178
179 # overlapping fields on multiple indices is supported by internally prefixing the field
180 # names with the index class to which they belong or, optionally, a user-provided alias
181 # for the index.
182 for index_cls in self.Meta.index_classes:
183 prefix = ""
184 if prefix_field_names:
185 prefix = "_%s__" % self._get_index_class_name(index_cls)
186 for field_name, field_type in six.iteritems(index_cls.fields):
187 orig_name = field_name
188 field_name = "%s%s" % (prefix, field_name)
189
190 # Don't use this field if it is in `ignore_fields`
191 if orig_name in ignore_fields or field_name in ignore_fields:
192 continue
193 # When fields to include are decided by `exclude`
194 if exclude:
195 if orig_name in exclude or field_name in exclude:
196 continue
197 # When fields to include are decided by `fields`
198 if fields:
199 if orig_name not in fields and field_name not in fields:
200 continue
201
202 # Look up the field attributes on the current index model,
203 # in order to correctly instantiate the serializer field.
204 model = index_cls().get_model()
205 kwargs = self._get_default_field_kwargs(model, field_type)
206 kwargs['prefix_field_names'] = prefix_field_names
207 field_mapping[field_name] = self._field_mapping[field_type](**kwargs)
208
209 # Add any explicitly declared fields. They *will* override any index fields
210 # in case of naming collision!.
211 if declared_fields:
212 for field_name in declared_fields:
213 field_mapping[field_name] = declared_fields[field_name]
214 return field_mapping
215
216 def to_representation(self, instance):
217 """
218 If we have a serializer mapping, use that. Otherwise, use standard serializer behavior
219 Since we might be dealing with multiple indexes, some fields might
220 not be valid for all results. Do not render the fields which don't belong
221 to the search result.
222 """
223 if self.Meta.serializers:
224 ret = self.multi_serializer_representation(instance)
225 else:
226 ret = super(HaystackSerializer, self).to_representation(instance)
227 prefix_field_names = len(getattr(self.Meta, "index_classes")) > 1
228 current_index = self._get_index_class_name(type(instance.searchindex))
229 for field in self.fields.keys():
230 orig_field = field
231 if prefix_field_names:
232 parts = field.split("__")
233 if len(parts) > 1:
234 index = parts[0][1:] # trim the preceding '_'
235 field = parts[1]
236 if index == current_index:
237 ret[field] = ret[orig_field]
238 del ret[orig_field]
239 elif field not in chain(instance.searchindex.fields.keys(), self._declared_fields.keys()):
240 del ret[orig_field]
241
242 # include the highlighted field in either case
243 if getattr(instance, "highlighted", None):
244 ret["highlighted"] = instance.highlighted[0]
245 return ret
246
247 def multi_serializer_representation(self, instance):
248 serializers = self.Meta.serializers
249 index = instance.searchindex
250 serializer_class = serializers.get(type(index), None)
251 if not serializer_class:
252 raise ImproperlyConfigured("Could not find serializer for %s in mapping" % index)
253 return serializer_class(context=self._context).to_representation(instance)
254
255
256 class FacetFieldSerializer(serializers.Serializer):
257 """
258 Responsible for serializing a faceted result.
259 """
260
261 text = serializers.SerializerMethodField()
262 count = serializers.SerializerMethodField()
263 narrow_url = serializers.SerializerMethodField()
264
265 def __init__(self, *args, **kwargs):
266 self._parent_field = None
267 super(FacetFieldSerializer, self).__init__(*args, **kwargs)
268
269 @property
270 def parent_field(self):
271 return self._parent_field
272
273 @parent_field.setter
274 def parent_field(self, value):
275 self._parent_field = value
276
277 def get_paginate_by_param(self):
278 """
279 Returns the ``paginate_by_param`` for the (root) view paginator class.
280 This is needed in order to remove the query parameter from faceted
281 narrow urls.
282
283 If using a custom pagination class, this class attribute needs to
284 be set manually.
285 """
286 if hasattr(self.root, "paginate_by_param") and self.root.paginate_by_param:
287 return self.root.paginate_by_param
288
289 pagination_class = self.context["view"].pagination_class
290 if not pagination_class:
291 return None
292
293 # PageNumberPagination
294 if hasattr(pagination_class, "page_query_param"):
295 return pagination_class.page_query_param
296
297 # LimitOffsetPagination
298 elif hasattr(pagination_class, "offset_query_param"):
299 return pagination_class.offset_query_param
300
301 # CursorPagination
302 elif hasattr(pagination_class, "cursor_query_param"):
303 return pagination_class.cursor_query_param
304
305 else:
306 raise AttributeError(
307 "%(root_cls)s is missing a `paginate_by_param` attribute. "
308 "Define a %(root_cls)s.paginate_by_param or override "
309 "%(cls)s.get_paginate_by_param()." % {
310 "root_cls": self.root.__class__.__name__,
311 "cls": self.__class__.__name__
312 })
313
314 def get_text(self, instance):
315 """
316 Haystack facets are returned as a two-tuple (value, count).
317 The text field should contain the faceted value.
318 """
319 instance = instance[0]
320 if isinstance(instance, (six.text_type, six.string_types)):
321 return serializers.CharField(read_only=True).to_representation(instance)
322 elif isinstance(instance, datetime):
323 return serializers.DateTimeField(read_only=True).to_representation(instance)
324 return instance
325
326 def get_count(self, instance):
327 """
328 Haystack facets are returned as a two-tuple (value, count).
329 The count field should contain the faceted count.
330 """
331 instance = instance[1]
332 return serializers.IntegerField(read_only=True).to_representation(instance)
333
334 def get_narrow_url(self, instance):
335 """
336 Return a link suitable for narrowing on the current item.
337 """
338 text = instance[0]
339 request = self.context["request"]
340 query_params = request.GET.copy()
341
342 # Never keep the page query parameter in narrowing urls.
343 # It will raise a NotFound exception when trying to paginate a narrowed queryset.
344 page_query_param = self.get_paginate_by_param()
345 if page_query_param and page_query_param in query_params:
346 del query_params[page_query_param]
347
348 selected_facets = set(query_params.pop(self.root.facet_query_params_text, []))
349 selected_facets.add("%(field)s_exact:%(text)s" % {"field": self.parent_field, "text": text})
350 query_params.setlist(self.root.facet_query_params_text, sorted(selected_facets))
351
352 path = "%(path)s?%(query)s" % {"path": request.path_info, "query": query_params.urlencode()}
353 url = request.build_absolute_uri(path)
354 return serializers.Hyperlink(url, "narrow-url")
355
356 def to_representation(self, field, instance):
357 """
358 Set the ``parent_field`` property equal to the current field on the serializer class,
359 so that each field can query it to see what kind of attribute they are processing.
360 """
361 self.parent_field = field
362 return super(FacetFieldSerializer, self).to_representation(instance)
363
364
365 class HaystackFacetSerializer(six.with_metaclass(HaystackSerializerMeta, serializers.Serializer)):
366 """
367 The ``HaystackFacetSerializer`` is used to serialize the ``facet_counts()``
368 dictionary results on a ``SearchQuerySet`` instance.
369 """
370
371 _abstract = True
372 serialize_objects = False
373 paginate_by_param = None
374 facet_dict_field_class = FacetDictField
375 facet_list_field_class = FacetListField
376 facet_field_serializer_class = FacetFieldSerializer
377
378 def get_fields(self):
379 """
380 This returns a dictionary containing the top most fields,
381 ``dates``, ``fields`` and ``queries``.
382 """
383 field_mapping = OrderedDict()
384 for field, data in self.instance.items():
385 field_mapping.update(
386 {field: self.facet_dict_field_class(
387 child=self.facet_list_field_class(child=self.facet_field_serializer_class(data)), required=False)}
388 )
389
390 if self.serialize_objects is True:
391 field_mapping["objects"] = serializers.SerializerMethodField()
392
393 return field_mapping
394
395 def get_objects(self, instance):
396 """
397 Return a list of objects matching the faceted result.
398 """
399 view = self.context["view"]
400 queryset = self.context["objects"]
401
402 page = view.paginate_queryset(queryset)
403 if page is not None:
404 serializer = view.get_facet_objects_serializer(page, many=True)
405 return OrderedDict([
406 ("count", self.get_count(queryset)),
407 ("next", view.paginator.get_next_link()),
408 ("previous", view.paginator.get_previous_link()),
409 ("results", serializer.data)
410 ])
411
412 serializer = view.get_serializer(queryset, many=True)
413 return serializer.data
414
415 def get_count(self, queryset):
416 """
417 Determine an object count, supporting either querysets or regular lists.
418 """
419 try:
420 return queryset.count()
421 except (AttributeError, TypeError):
422 return len(queryset)
423
424 @property
425 def facet_query_params_text(self):
426 return self.context["facet_query_params_text"]
427
428
429 class HaystackSerializerMixin(object):
430 """
431 This mixin can be added to a serializer to use the actual object as the data source for serialization rather
432 than the data stored in the search index fields. This makes it easy to return data from search results in
433 the same format as elsewhere in your API and reuse your existing serializers
434 """
435
436 def to_representation(self, instance):
437 obj = instance.object
438 return super(HaystackSerializerMixin, self).to_representation(obj)
439
440
441 class HighlighterMixin(object):
442 """
443 This mixin adds support for ``highlighting`` (the pure python, portable
444 version, not SearchQuerySet().highlight()). See Haystack docs
445 for more info).
446 """
447
448 highlighter_class = Highlighter
449 highlighter_css_class = "highlighted"
450 highlighter_html_tag = "span"
451 highlighter_max_length = 200
452 highlighter_field = None
453
454 def get_highlighter(self):
455 if not self.highlighter_class:
456 raise ImproperlyConfigured(
457 "%(cls)s is missing a highlighter_class. Define %(cls)s.highlighter_class, "
458 "or override %(cls)s.get_highlighter()." %
459 {"cls": self.__class__.__name__}
460 )
461 return self.highlighter_class
462
463 @staticmethod
464 def get_document_field(instance):
465 """
466 Returns which field the search index has marked as it's
467 `document=True` field.
468 """
469 for name, field in instance.searchindex.fields.items():
470 if field.document is True:
471 return name
472
473 def get_terms(self, data):
474 """
475 Returns the terms to be highlighted
476 """
477 terms = " ".join(six.itervalues(self.context["request"].GET))
478 return terms
479
480 def to_representation(self, instance):
481 ret = super(HighlighterMixin, self).to_representation(instance)
482 terms = self.get_terms(ret)
483 if terms:
484 highlighter = self.get_highlighter()(terms, **{
485 "html_tag": self.highlighter_html_tag,
486 "css_class": self.highlighter_css_class,
487 "max_length": self.highlighter_max_length
488 })
489 document_field = self.get_document_field(instance)
490 if highlighter and document_field:
491 # Handle case where this data is None, but highlight expects it to be a string
492 data_to_highlight = getattr(instance, self.highlighter_field or document_field) or ''
493 ret["highlighted"] = highlighter.highlight(data_to_highlight)
494 return ret