Django Haystack

3.3.0 · active · verified Thu Apr 16

Django Haystack is a pluggable search solution for Django applications, providing a unified API to various search backends like Solr, Elasticsearch, and Whoosh. The latest version, 3.3.0, offers official support for Django 3.x, 4.x, and 5.x, and is compatible with Python 3.8-3.12. Releases are primarily driven by new Django version compatibility.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up minimal Django settings for Haystack and perform basic search queries using `SearchQuerySet`. Note that for actual results, you need a full Django project with models, SearchIndexes defined, and the `python manage.py rebuild_index` command executed to populate the search index.

import os
from django.conf import settings

# Minimal Django settings configuration required for Haystack's imports
# and internal mechanisms to initialize.
if not settings.configured:
    settings.configure(
        INSTALLED_APPS=[
            'haystack',
            # 'your_app_with_models_and_search_indexes', # Add your app here in a real project
        ],
        BASE_DIR=os.path.dirname(os.path.abspath(__file__)),
        HAYSTACK_CONNECTIONS={
            'default': {
                'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
                'PATH': os.path.join(os.path.dirname(os.path.abspath(__file__)), 'whoosh_index'),
            }
        },
        SECRET_KEY=os.environ.get('DJANGO_SECRET_KEY', 'a-very-secret-key-for-demo'),
        DEBUG=True,
        TIME_ZONE='UTC',
        USE_TZ=True,
        DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}
    )

# Haystack requires Django apps to be ready to correctly discover indexes
import django
django.setup()

# Now we can import SearchQuerySet
from haystack.query import SearchQuerySet

# IMPORTANT: In a real Django project, before this code yields results, you would need:
# 1. A Django model (e.g., `myapp/models.py`)
# 2. A Haystack SearchIndex for your model (e.g., `myapp/search_indexes.py`)
# 3. Your app added to INSTALLED_APPS in settings.py
# 4. You would have run `./manage.py rebuild_index` to populate the search index.

print("Attempting to perform a search query (requires a populated index to show results)...\n")

try:
    # Example 1: Filtering search results
    # Assumes your SearchIndex has 'content' and 'pub_date' fields.
    results = SearchQuerySet().filter(content='example').order_by('-pub_date')

    if results:
        print(f"Found {len(results)} results for 'example':")
        for result in results:
            # result.object would give you the actual Django model instance in a real project
            print(f"  Title: {getattr(result, 'title', 'N/A')}, Content: {getattr(result, 'content', 'N/A')}, Model: {result.model_name}")
    else:
        print("No results found for 'example'. (Requires a populated search index.)")

    # Example 2: Auto-query (searches across the default 'text' field)
    more_results = SearchQuerySet().auto_query('another note').models('Note').load_all()
    print(f"\nFound {len(more_results)} results for 'another note' in 'Note' model (auto_query):")
    for result in more_results:
        print(f"  Title: {getattr(result, 'title', 'N/A')}")

except Exception as e:
    print(f"An error occurred during search: {e}")
    print("\nTroubleshooting: ")
    print("1. Ensure you have installed a specific search backend, e.g., `pip install 'django-haystack[whoosh]'`")
    print("2. Ensure you have run `./manage.py rebuild_index` in your Django project to populate the index.")

view raw JSON →