drf_haystack.fields

class drf_haystack.fields.DRFHaystackFieldMixin(**kwargs)[source]

Bases: object

bind(field_name, parent)[source]

Initializes the field name and parent for the field instance. Called when a field is added to the parent serializer instance. Taken from DRF and modified to support drf_haystack multiple index functionality.

convert_field_name(field_name)[source]
prefix_field_names = False
class drf_haystack.fields.FacetDictField(*args, **kwargs)[source]

Bases: rest_framework.fields.DictField

A special DictField which passes the key attribute down to the children’s to_representation() in order to let the serializer know what field they’re currently processing.

to_representation(value)[source]

List of object instances -> List of dicts of primitive datatypes.

class drf_haystack.fields.FacetListField(*args, **kwargs)[source]

Bases: rest_framework.fields.ListField

The FacetListField just pass along the key derived from FacetDictField.

to_representation(key, data)[source]

List of object instances -> List of dicts of primitive datatypes.

class drf_haystack.fields.HaystackBooleanField(**kwargs)[source]

Bases: drf_haystack.fields.DRFHaystackFieldMixin, rest_framework.fields.BooleanField

class drf_haystack.fields.HaystackCharField(**kwargs)[source]

Bases: drf_haystack.fields.DRFHaystackFieldMixin, rest_framework.fields.CharField

class drf_haystack.fields.HaystackDateField(**kwargs)[source]

Bases: drf_haystack.fields.DRFHaystackFieldMixin, rest_framework.fields.DateField

class drf_haystack.fields.HaystackDateTimeField(**kwargs)[source]

Bases: drf_haystack.fields.DRFHaystackFieldMixin, rest_framework.fields.DateTimeField

class drf_haystack.fields.HaystackDecimalField(**kwargs)[source]

Bases: drf_haystack.fields.DRFHaystackFieldMixin, rest_framework.fields.DecimalField

class drf_haystack.fields.HaystackFloatField(**kwargs)[source]

Bases: drf_haystack.fields.DRFHaystackFieldMixin, rest_framework.fields.FloatField

class drf_haystack.fields.HaystackIntegerField(**kwargs)[source]

Bases: drf_haystack.fields.DRFHaystackFieldMixin, rest_framework.fields.IntegerField

class drf_haystack.fields.HaystackMultiValueField(**kwargs)[source]

Bases: drf_haystack.fields.DRFHaystackFieldMixin, rest_framework.fields.ListField

drf_haystack.filters

class drf_haystack.filters.BaseHaystackFilterBackend[source]

Bases: rest_framework.filters.BaseFilterBackend

A base class from which all Haystack filter backend classes should inherit.

apply_filters(queryset, applicable_filters=None, applicable_exclusions=None)[source]

Apply constructed filters and excludes and return the queryset

Parameters:
  • queryset – queryset to filter
  • applicable_filters – filters which are passed directly to queryset.filter()
  • applicable_exclusions – filters which are passed directly to queryset.exclude()

:returns filtered queryset

build_filters(view, filters=None)[source]

Get the query builder instance and return constructed query filters.

filter_queryset(request, queryset, view)[source]

Return the filtered queryset.

get_query_builder(*args, **kwargs)[source]

Return the query builder class instance that should be used to build the query which is passed to the search engine backend.

get_query_builder_class()[source]

Return the class to use for building the query. Defaults to using self.query_builder_class.

You may want to override this if you need to provide different methods of building the query sent to the search engine backend.

static get_request_filters(request)[source]
process_filters(filters, queryset, view)[source]

Convenient hook to do any post-processing of the filters before they are applied to the queryset.

query_builder_class = None
class drf_haystack.filters.HaystackAutocompleteFilter[source]

Bases: drf_haystack.filters.HaystackFilter

A filter backend to perform autocomplete search.

Must be run against fields that are either NgramField or EdgeNgramField.

process_filters(filters, queryset, view)[source]

Convenient hook to do any post-processing of the filters before they are applied to the queryset.

class drf_haystack.filters.HaystackBoostFilter[source]

Bases: drf_haystack.filters.BaseHaystackFilterBackend

Filter backend for applying term boost on query time.

Apply by adding a comma separated boost query parameter containing a the term you want to boost and a floating point or integer for the boost value. The boost value is based around 1.0 as 100% - no boost.

Gives a slight increase in relevance for documents that include “banana”:
/api/v1/search/?boost=banana,1.1
apply_filters(queryset, applicable_filters=None, applicable_exclusions=None)[source]

Apply constructed filters and excludes and return the queryset

Parameters:
  • queryset – queryset to filter
  • applicable_filters – filters which are passed directly to queryset.filter()
  • applicable_exclusions – filters which are passed directly to queryset.exclude()

:returns filtered queryset

filter_queryset(request, queryset, view)[source]

Return the filtered queryset.

query_builder_class

alias of drf_haystack.query.BoostQueryBuilder

query_param = 'boost'
class drf_haystack.filters.HaystackFacetFilter[source]

Bases: drf_haystack.filters.BaseHaystackFilterBackend

Filter backend for faceting search results. This backend does not apply regular filtering.

Faceting field options can be set by using the field_options attribute on the serializer, and can be overridden by query parameters. Dates will be parsed by the python-dateutil.parser() which can handle most date formats.

Query parameters is parsed in the following format:
?field1=option1:value1,option2:value2&field2=option1:value1,option2:value2

where each options key:value pair is separated by the view.lookup_sep attribute.

apply_filters(queryset, applicable_filters=None, applicable_exclusions=None)[source]

Apply faceting to the queryset

filter_queryset(request, queryset, view)[source]

Return the filtered queryset.

query_builder_class

alias of drf_haystack.query.FacetQueryBuilder

class drf_haystack.filters.HaystackFilter[source]

Bases: drf_haystack.filters.BaseHaystackFilterBackend

A filter backend that compiles a haystack compatible filtering query.

default_operator()

and_(a, b) – Same as a & b.

query_builder_class

alias of drf_haystack.query.FilterQueryBuilder

class drf_haystack.filters.HaystackGEOSpatialFilter[source]

Bases: drf_haystack.filters.BaseHaystackFilterBackend

A base filter backend for doing geo spatial filtering. If using this filter make sure to provide a point_field with the name of your the LocationField of your index.

We’ll always do the somewhat slower but more accurate dwithin (radius) filter.

apply_filters(queryset, applicable_filters=None, applicable_exclusions=None)[source]

Apply constructed filters and excludes and return the queryset

Parameters:
  • queryset – queryset to filter
  • applicable_filters – filters which are passed directly to queryset.filter()
  • applicable_exclusions – filters which are passed directly to queryset.exclude()

:returns filtered queryset

filter_queryset(request, queryset, view)[source]

Return the filtered queryset.

point_field = 'coordinates'
query_builder_class

alias of drf_haystack.query.SpatialQueryBuilder

class drf_haystack.filters.HaystackHighlightFilter[source]

Bases: drf_haystack.filters.HaystackFilter

A filter backend which adds support for highlighting on the SearchQuerySet level (the fast one). Note that you need to use a search backend which supports highlighting in order to use this.

This will add a hightlighted entry to your response, encapsulating the highlighted words in an <em>highlighted results</em> block.

filter_queryset(request, queryset, view)[source]

Return the filtered queryset.

class drf_haystack.filters.HaystackOrderingFilter[source]

Bases: rest_framework.filters.OrderingFilter

Some docstring here!

get_default_valid_fields(queryset, view, context={})[source]
get_valid_fields(queryset, view, context={})[source]

drf_haystack.generics

class drf_haystack.generics.HaystackGenericAPIView(**kwargs)[source]

Bases: rest_framework.generics.GenericAPIView

Base class for all haystack generic views.

document_uid_field = 'id'
filter_backends = [<class 'drf_haystack.filters.HaystackFilter'>]
filter_queryset(queryset)[source]

Given a queryset, filter it with whichever filter backend is in use.

You are unlikely to want to override this method, although you may need to call it either from a list view, or from a custom get_object method if you want to apply the configured filtering backend to the default queryset.

get_object()[source]

Fetch a single document from the data store according to whatever unique identifier is available for that document in the SearchIndex.

In cases where the view has multiple index_models, add a model query parameter containing a single app_label.model name to the request in order to override which model to include in the SearchQuerySet.

Example:
/api/v1/search/42/?model=myapp.person
get_queryset(index_models=[])[source]

Get the list of items for this view. Returns self.queryset if defined and is a self.object_class instance.

@:param index_models: override self.index_models

index_models = []
load_all = False
lookup_sep = ','
object_class

alias of haystack.query.SearchQuerySet

query_object

alias of haystack.backends.SQ

drf_haystack.mixins

class drf_haystack.mixins.FacetMixin[source]

Bases: object

Mixin class for supporting faceting on an API View.

facet_filter_backends = [<class 'drf_haystack.filters.HaystackFacetFilter'>]
facet_objects_serializer_class = None
facet_query_params_text = 'selected_facets'
facet_serializer_class = None
facets(request)[source]

Sets up a list route for faceted results. This will add ie ^search/facets/$ to your existing ^search pattern.

filter_facet_queryset(queryset)[source]

Given a search queryset, filter it with whichever facet filter backends in use.

get_facet_objects_serializer(*args, **kwargs)[source]

Return the serializer instance which should be used for serializing faceted objects.

get_facet_objects_serializer_class()[source]

Return the class to use for serializing faceted objects. Defaults to using the views self.serializer_class if not self.facet_objects_serializer_class is set.

get_facet_serializer(*args, **kwargs)[source]

Return the facet serializer instance that should be used for serializing faceted output.

get_facet_serializer_class()[source]

Return the class to use for serializing facets. Defaults to using self.facet_serializer_class.

class drf_haystack.mixins.MoreLikeThisMixin[source]

Bases: object

Mixin class for supporting “more like this” on an API View.

more_like_this(request, pk=None)[source]

Sets up a detail route for more-like-this results. Note that you’ll need backend support in order to take advantage of this.

This will add ie. ^search/{pk}/more-like-this/$ to your existing ^search pattern.

drf_haystack.query

class drf_haystack.query.BaseQueryBuilder(backend, view)[source]

Bases: object

Query builder base class.

build_query(**filters)[source]
Parameters:list[str]] filters (dict[str,) – is an expanded QueryDict or a mapping of keys to a list of parameters.
static tokenize(stream, separator)[source]

Tokenize and yield query parameter values.

Parameters:
  • stream – Input value
  • separator – Character to use to separate the tokens.
Returns:

class drf_haystack.query.BoostQueryBuilder(backend, view)[source]

Bases: drf_haystack.query.BaseQueryBuilder

Query builder class for adding boost to queries.

build_query(**filters)[source]
Parameters:list[str]] filters (dict[str,) – is an expanded QueryDict or

a mapping of keys to a list of parameters.

class drf_haystack.query.FacetQueryBuilder(backend, view)[source]

Bases: drf_haystack.query.BaseQueryBuilder

Query builder class suitable for constructing faceted queries.

build_query(**filters)[source]

Creates a dict of dictionaries suitable for passing to the SearchQuerySet facet, date_facet or query_facet method. All key word arguments should be wrapped in a list.

Parameters:
  • view – API View
  • list[str]] filters (dict[str,) – is an expanded QueryDict or a mapping

of keys to a list of parameters.

parse_field_options(*options)[source]

Parse the field options query string and return it as a dictionary.

class drf_haystack.query.FilterQueryBuilder(backend, view)[source]

Bases: drf_haystack.query.BaseQueryBuilder

Query builder class suitable for doing basic filtering.

build_query(**filters)[source]

Creates a single SQ filter from querystring parameters that correspond to the SearchIndex fields that have been “registered” in view.fields.

Default behavior is to OR terms for the same parameters, and AND between parameters. Any querystring parameters that are not registered in view.fields will be ignored.

Parameters:list[str]] filters (dict[str,) – is an expanded QueryDict or a mapping of keys to a list of

parameters.

class drf_haystack.query.SpatialQueryBuilder(backend, view)[source]

Bases: drf_haystack.query.BaseQueryBuilder

Query builder class suitable for construction spatial queries.

build_query(**filters)[source]

Build queries for geo spatial filtering.

Expected query parameters are:
  • a unit=value parameter where the unit is a valid UNIT in the django.contrib.gis.measure.Distance class.
  • from which must be a comma separated latitude and longitude.
Example query:

/api/v1/search/?km=10&from=59.744076,10.152045

Will perform a dwithin query within 10 km from the point with latitude 59.744076 and longitude 10.152045.

drf_haystack.serializers

class drf_haystack.serializers.FacetFieldSerializer(*args, **kwargs)[source]

Bases: rest_framework.serializers.Serializer

Responsible for serializing a faceted result.

get_count(instance)[source]

Haystack facets are returned as a two-tuple (value, count). The count field should contain the faceted count.

get_narrow_url(instance)[source]

Return a link suitable for narrowing on the current item.

get_paginate_by_param()[source]

Returns the paginate_by_param for the (root) view paginator class. This is needed in order to remove the query parameter from faceted narrow urls.

If using a custom pagination class, this class attribute needs to be set manually.

get_text(instance)[source]

Haystack facets are returned as a two-tuple (value, count). The text field should contain the faceted value.

parent_field
to_representation(field, instance)[source]

Set the parent_field property equal to the current field on the serializer class, so that each field can query it to see what kind of attribute they are processing.

class drf_haystack.serializers.HaystackFacetSerializer(instance=None, data=<class 'rest_framework.fields.empty'>, **kwargs)[source]

Bases: rest_framework.serializers.Serializer

The HaystackFacetSerializer is used to serialize the facet_counts() dictionary results on a SearchQuerySet instance.

facet_dict_field_class

alias of drf_haystack.fields.FacetDictField

facet_field_serializer_class

alias of FacetFieldSerializer

facet_list_field_class

alias of drf_haystack.fields.FacetListField

facet_query_params_text
get_count(queryset)[source]

Determine an object count, supporting either querysets or regular lists.

get_fields()[source]

This returns a dictionary containing the top most fields, dates, fields and queries.

get_objects(instance)[source]

Return a list of objects matching the faceted result.

paginate_by_param = None
serialize_objects = False
class drf_haystack.serializers.HaystackSerializer(instance=None, data=<class 'rest_framework.fields.empty'>, **kwargs)[source]

Bases: rest_framework.serializers.Serializer

A HaystackSerializer which populates fields based on which models that are available in the SearchQueryset.

get_fields()[source]

Get the required fields for serializing the result.

multi_serializer_representation(instance)[source]
to_representation(instance)[source]

If we have a serializer mapping, use that. Otherwise, use standard serializer behavior Since we might be dealing with multiple indexes, some fields might not be valid for all results. Do not render the fields which don’t belong to the search result.

class drf_haystack.serializers.HaystackSerializerMeta[source]

Bases: rest_framework.serializers.SerializerMetaclass

Metaclass for the HaystackSerializer that ensures that all declared subclasses implemented a Meta.

class drf_haystack.serializers.HaystackSerializerMixin[source]

Bases: object

This mixin can be added to a serializer to use the actual object as the data source for serialization rather than the data stored in the search index fields. This makes it easy to return data from search results in the same format as elsewhere in your API and reuse your existing serializers

to_representation(instance)[source]
class drf_haystack.serializers.HighlighterMixin[source]

Bases: object

This mixin adds support for highlighting (the pure python, portable version, not SearchQuerySet().highlight()). See Haystack docs for more info).

static get_document_field(instance)[source]

Returns which field the search index has marked as it’s document=True field.

get_highlighter()[source]
highlighter_class

alias of haystack.utils.highlighting.Highlighter

highlighter_css_class = 'highlighted'
highlighter_field = None
highlighter_html_tag = 'span'
highlighter_max_length = 200
to_representation(instance)[source]
class drf_haystack.serializers.Meta[source]

Bases: type

Template for the HaystackSerializerMeta.Meta class.

exclude = ()
field_aliases = {}
field_options = {}
fields = ()
ignore_fields = ()
index_aliases = {}
index_classes = ()
search_fields = ()
serializers = ()

drf_haystack.utils

drf_haystack.utils.merge_dict(a, b)[source]

Recursively merges and returns dict a with dict b. Any list values will be combined and returned sorted.

Parameters:
  • a – dictionary object
  • b – dictionary object
Returns:

merged dictionary object

drf_haystack.viewsets

class drf_haystack.viewsets.HaystackViewSet(**kwargs)[source]

Bases: rest_framework.mixins.RetrieveModelMixin, rest_framework.mixins.ListModelMixin, rest_framework.viewsets.ViewSetMixin, drf_haystack.generics.HaystackGenericAPIView

The HaystackViewSet class provides the default list() and retrieve() actions with a haystack index as it’s data source.