| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
from __future__ import absolute_import, unicode_literals |
| 4 |
|
| 5 |
import six |
| 6 |
|
| 7 |
from django.contrib.contenttypes.models import ContentType |
| 8 |
from django.http import Http404 |
| 9 |
|
| 10 |
from haystack.backends import SQ |
| 11 |
from haystack.query import SearchQuerySet |
| 12 |
from rest_framework.generics import GenericAPIView |
| 13 |
|
| 14 |
from drf_haystack.filters import HaystackFilter |
| 15 |
|
| 16 |
|
| 17 |
class HaystackGenericAPIView(GenericAPIView): |
| 18 |
""" |
| 19 |
Base class for all haystack generic views. |
| 20 |
""" |
| 21 |
# Use `index_models` to filter on which search index models we |
| 22 |
# should include in the search result. |
| 23 |
index_models = [] |
| 24 |
|
| 25 |
object_class = SearchQuerySet |
| 26 |
query_object = SQ |
| 27 |
|
| 28 |
# Override document_uid_field with whatever field in your index |
| 29 |
# you use to uniquely identify a single document. This value will be |
| 30 |
# used wherever the view references the `lookup_field` kwarg. |
| 31 |
document_uid_field = "id" |
| 32 |
lookup_sep = "," |
| 33 |
|
| 34 |
# If set to False, DB lookups are done on a per-object basis, |
| 35 |
# resulting in in many individual trips to the database. If True, |
| 36 |
# the SearchQuerySet will group similar objects into a single query. |
| 37 |
load_all = False |
| 38 |
|
| 39 |
filter_backends = [HaystackFilter] |
| 40 |
|
| 41 |
def get_queryset(self, index_models=[]): |
| 42 |
""" |
| 43 |
Get the list of items for this view. |
| 44 |
Returns ``self.queryset`` if defined and is a ``self.object_class`` |
| 45 |
instance. |
| 46 |
|
| 47 |
@:param index_models: override `self.index_models` |
| 48 |
""" |
| 49 |
if self.queryset is not None and isinstance(self.queryset, self.object_class): |
| 50 |
queryset = self.queryset.all() |
| 51 |
else: |
| 52 |
queryset = self.object_class()._clone() |
| 53 |
if len(index_models): |
| 54 |
queryset = queryset.models(*index_models) |
| 55 |
elif len(self.index_models): |
| 56 |
queryset = queryset.models(*self.index_models) |
| 57 |
return queryset |
| 58 |
|
| 59 |
def get_object(self): |
| 60 |
""" |
| 61 |
Fetch a single document from the data store according to whatever |
| 62 |
unique identifier is available for that document in the |
| 63 |
SearchIndex. |
| 64 |
|
| 65 |
In cases where the view has multiple ``index_models``, add a ``model`` query |
| 66 |
parameter containing a single `app_label.model` name to the request in order |
| 67 |
to override which model to include in the SearchQuerySet. |
| 68 |
|
| 69 |
Example: |
| 70 |
/api/v1/search/42/?model=myapp.person |
| 71 |
""" |
| 72 |
queryset = self.get_queryset() |
| 73 |
if "model" in self.request.query_params: |
| 74 |
try: |
| 75 |
app_label, model = map(six.text_type.lower, self.request.query_params["model"].split(".", 1)) |
| 76 |
ctype = ContentType.objects.get(app_label=app_label, model=model) |
| 77 |
queryset = self.get_queryset(index_models=[ctype.model_class()]) |
| 78 |
except (ValueError, ContentType.DoesNotExist): |
| 79 |
raise Http404("Could not find any models matching '%s'. Make sure to use a valid " |
| 80 |
"'app_label.model' name for the 'model' query parameter." % self.request.query_params["model"]) |
| 81 |
|
| 82 |
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field |
| 83 |
if lookup_url_kwarg not in self.kwargs: |
| 84 |
raise AttributeError( |
| 85 |
"Expected view %s to be called with a URL keyword argument " |
| 86 |
"named '%s'. Fix your URL conf, or set the `.lookup_field` " |
| 87 |
"attribute on the view correctly." % (self.__class__.__name__, lookup_url_kwarg) |
| 88 |
) |
| 89 |
queryset = queryset.filter(self.query_object((self.document_uid_field, self.kwargs[lookup_url_kwarg]))) |
| 90 |
count = queryset.count() |
| 91 |
if count == 1: |
| 92 |
return queryset[0] |
| 93 |
elif count > 1: |
| 94 |
raise Http404("Multiple results matches the given query. Expected a single result.") |
| 95 |
|
| 96 |
raise Http404("No result matches the given query.") |
| 97 |
|
| 98 |
def filter_queryset(self, queryset): |
| 99 |
queryset = super(HaystackGenericAPIView, self).filter_queryset(queryset) |
| 100 |
|
| 101 |
if self.load_all: |
| 102 |
queryset = queryset.load_all() |
| 103 |
|
| 104 |
return queryset |