Skip to content
Robert Rollins edited this page Aug 5, 2023 · 34 revisions

Getting started with django-watson

To install django-watson, follow these steps:

  1. Install django-watson using pip: pip install django-watson.
  2. Add 'watson' to your INSTALLED_APPS setting.
  3. Update your Database with manage.py migrate.
  4. Run the command manage.py installwatson.
  5. (Optional) Add watson.middleware.SearchContextMiddleware to your middlewares for more efficient search index updates.

Existing website data: If you're integrating django-watson with an existing site, you'll also want to run ./manage.py buildwatson to index your existing data once you've registered all the models you want to search for, as described next.

Registering models with django-watson

To use django-watson to search your models, you first need to tell it which models to include in its indices. To do this, simply call search.register() for each of the models you want to index. A good place to do this is in your application's AppConfig:

In your_app/apps.py

from django.apps import AppConfig
from watson import search

class YourAppConfig(AppConfig):
    name = "your_app"
    def ready(self):
        YourModel = self.get_model("YourModel")
        search.register(YourModel)

To learn more about configuring applications, please check the Django documentation.

Once you've registered your models with django-watson, run the command manage.py buildwatson to register any existing instances of those models in your database. From now on, any additions, creations, or deletions you make will be automatically applied to watson's indices. Thus, this command only needs to be run whenever you add a new model to django-watson.

For more information about registering models with django-watson, please visit the registering models wiki page.

Searching for models

You can search for any registered models using the search.search() method:

from watson import search

search_results = search.search("Your search text")

for result in search_results:
    print result.title, result.url, result.meta.some_field

result is a watson object in this context. You will not be able to access your objects' attributes through it. In case you want to do so, use search.filter() instead:

from watson import search

search_results = search.filter(YourModel, "Your search text")

for result in search_results:
    print result.your_model_attribute_1, result.your_model_attribute_2

Keep in mind that this will limit the search results to one model only. You will have to use the watson objects from search.search() if you want to include several models. Read the documentation below for more information.

For more information about searching for models with django-watson, please visit the searching models wiki page.

More information