Django Model Search

1.2.0 · active · verified Thu Apr 09

django-modelsearch is a Python library that enables indexing Django models with various search backends, including Elasticsearch, OpenSearch, and the database itself (PostgreSQL, MySQL). It provides a unified API for searching models, inspired by Wagtail Search. The current version is 1.2.0, with releases occurring periodically to support Django and backend updates.

Warnings

Install

Imports

Quickstart

Define a Django model with an inner `Search` class that specifies fields to index. Configure `MODELSEARCH_BACKENDS` in your Django settings. Use the `search()` method on your model's manager to query the index. Remember to run `manage.py update_index` after defining models or changing their data to populate the search index.

import os
from django.db import models
from modelsearch.base import Index
from modelsearch.fields import SearchField
from modelsearch.query import MatchAll
from django.conf import settings

# Minimal Django settings setup for quickstart, typically in settings.py
if not settings.configured:
    settings.configure(
        INSTALLED_APPS=[
            "modelsearch",
            "django.contrib.postgres" # For PostgreSQL DB search features
        ],
        MODELSEARCH_BACKENDS={
            "default": {
                "BACKEND": "modelsearch.backends.database.DatabaseSearchBackend"
                # "BACKEND": "modelsearch.backends.elasticsearch.ElasticsearchSearchBackend",
                # "URLS": [os.environ.get('ELASTICSEARCH_URL', 'http://localhost:9200')],
                # "INDEX": "test_modelsearch",
            }
        },
        DATABASES={
            "default": {
                "ENGINE": "django.db.backends.sqlite3",
                "NAME": ":memory:",
            }
        },
        SECRET_KEY="dummy-secret-key"
    )

# Define a Django Model
class Article(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()

    class Search(Index):
        fields = [
            SearchField("title", boost=10),
            SearchField("body"),
        ]

    def __str__(self):
        return self.title

# Example usage (run after Django setup and migrations)
# This part assumes a database is configured and tables are created.
# For a real application, you'd run `manage.py migrate` and then `manage.py update_index`.
if __name__ == "__main__":
    # In a real Django project, you'd import Article and use its manager.
    # For this isolated example, we simulate object creation.
    # Note: Search index update requires running `manage.py update_index` or calling backend manually.
    print("Quickstart will only demonstrate search query structure.")
    print("To run fully, ensure Django is setup, migrated, and index updated.")

    # Example search (using a dummy queryset for demonstration)
    # In a real app, this would be: `Article.objects.search("search term")`
    search_query = "example"
    # Simulate a search call
    class MockSearchManager:
        def search(self, query):
            print(f"Searching for: {query}")
            return ["MockResult1", "MockResult2"]

    mock_manager = MockSearchManager()

    print(f"\nSearch for '{search_query}':")
    results = mock_manager.search(search_query)
    print(f"Results: {results}")

    print("\nSearch for all with MatchAll():")
    results_all = mock_manager.search(MatchAll())
    print(f"Results: {results_all}")

view raw JSON →