Search code examples
pythondjangodjango-haystack

Specifying an alternate path for a Haystack template


The Haystack documentation states that:

Additionally, we’re providing use_template=True on the text field. This allows us to use a data template (rather than error-prone concatenation) to build the document the search engine will index. You’ll need to create a new template inside your template directory called search/indexes/myapp/note_text.txt

Unfortunately, there is no information on what to do if you want a differently named template.

Is it possible to specify the path to a haystack document template?


Solution

  • Dang it, I was searching for this for a week.

    Its listed under the SearchField API documentation, which is the superclass of the actual fields in a search index.

    SearchField.template_name

    Allows you to override the name of the template to use when preparing data. By default, the data templates for fields are located within your TEMPLATE_DIRS under a path like search/indexes/{app_label}/{model_name}_{field_name}.txt. This option lets you override that path (though still within TEMPLATE_DIRS).

    Example:

    bio = CharField(use_template=True, template_name='myapp/data/bio.txt')
    

    You can also provide a list of templates, as loader.select_template is used under the hood.

    Example:

    bio = CharField(use_template=True, template_name=['myapp/data/bio.txt', 'myapp/bio.txt', 'bio.txt'])